Initial project source

这个提交包含在:
apple
2026-11-20 15:32:57 +08:00
当前提交 fb47c07f7c
共修改 8405 个文件,包含 806907 行新增和 0 行删除
@@ -0,0 +1,15 @@
package cn.aixunkeji.datagov.governance;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
/** DataGov governance and metadata projection deployment unit. */
@SpringBootApplication
@EnableDubbo
public class AiXunGovernanceApplication {
public static void main(String[] args) {
SpringApplication.run(AiXunGovernanceApplication.class, args);
}
}
@@ -0,0 +1,19 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class AccessControlActorProvider {
Actor current() {
Long actorId = LoginHelper.getUserId();
Long departmentId = LoginHelper.getDeptId();
if (actorId == null || departmentId == null || actorId <= 0 || departmentId <= 0) {
throw AccessControlDomainException.forbidden();
}
return new Actor(actorId, departmentId, departmentId);
}
record Actor(long actorId, long organizationId, long departmentId) { }
}
@@ -0,0 +1,129 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import java.time.LocalDateTime;
import java.util.List;
final class AccessControlApi {
private AccessControlApi() {
}
enum PolicyStatus { DRAFT, ACTIVE, DEPRECATED, ARCHIVED }
enum ExecutionStatus { REGISTERED, NOT_ENFORCED, ENFORCED, UNSUPPORTED }
enum SubjectType { USER, ROLE, DEPARTMENT }
enum EngineType { HIVE, DORIS, MYSQL, MARIADB, POSTGRESQL, SQLSERVER, DAMENG, ORACLE }
enum EnforcementUnit {
PLATFORM_QUERY,
HIVE_TABLE_SELECT,
HIVE_PROTECTED_EXPORT,
HIVE_COLUMN_SELECT,
HIVE_ROW_FILTER,
HIVE_MASKING,
DORIS_TENANT_ROW_POLICY,
DORIS_COLUMN_SELECT,
DORIS_MASKING
}
enum AccessAction { SELECT, EXPORT }
enum RowOperator { EQUALS, NOT_EQUALS, IN, NOT_IN, IS_NULL, IS_NOT_NULL }
enum EvidenceKind { DISPATCH, READBACK, ALLOW, DENY }
enum EvidenceOutcome { DISPATCHED, MATCHED, ALLOWED, DENIED }
record RowCondition(String fieldRef, RowOperator operator, String valueRef) { }
record PurposeConstraint(
String purposeCode,
String scenarioRef,
String scopeRef,
LocalDateTime validFrom,
LocalDateTime validUntil,
List<AccessAction> allowedActions
) { }
record CreatePolicyCommand(
String policyCode,
String policyName,
SubjectType subjectType,
String subjectRef,
EngineType engineType,
EnforcementUnit enforcementUnit,
String resourceRef,
List<AccessAction> actions,
List<RowCondition> rowConditions,
List<String> columnRefs,
PurposeConstraint purpose
) { }
record UpdatePolicyCommand(
String policyName,
SubjectType subjectType,
String subjectRef,
EngineType engineType,
EnforcementUnit enforcementUnit,
String resourceRef,
List<AccessAction> actions,
List<RowCondition> rowConditions,
List<String> columnRefs,
PurposeConstraint purpose,
Long version
) { }
record PolicyStatusCommand(PolicyStatus targetStatus, String reason, Long version) { }
record PurposeCommand(PurposeConstraint purpose, Long version) { }
record EnforcementEvidence(
EvidenceKind kind,
EvidenceOutcome outcome,
String evidenceRef,
String externalPolicyRef,
LocalDateTime observedAt,
Boolean reliable,
String snapshotSha256
) { }
record VerificationCommand(Long policyVersion, List<EnforcementEvidence> evidence) { }
record PolicyView(
long policyId,
String policyCode,
String policyName,
SubjectType subjectType,
String subjectRef,
EngineType engineType,
EnforcementUnit enforcementUnit,
String resourceRef,
List<AccessAction> actions,
List<RowCondition> rowConditions,
List<String> columnRefs,
PurposeConstraint purpose,
PolicyStatus policyStatus,
ExecutionStatus executionStatus,
String executionReason,
long organizationId,
long departmentId,
long version,
LocalDateTime createTime,
LocalDateTime updateTime
) { }
record VerificationView(
long verificationId,
long policyId,
long policyVersion,
ExecutionStatus executionStatus,
String reasonCode,
String snapshotSha256,
List<EnforcementEvidence> evidence,
LocalDateTime verifiedAt
) { }
record WriteView<T>(String requestId, T result) { }
}
@@ -0,0 +1,29 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.datagov.governance.securityreview.SecurityPolicyReviewApi;
import cn.aixunkeji.datagov.governance.securityquery.NativePolicyRules;
import org.springframework.stereotype.Component;
import java.util.List;
import static cn.aixunkeji.datagov.governance.securityreview.SecurityPolicyReviewException.*;
@Component
public class AccessControlComparisonOwner {
private final AccessControlJdbcRepository repository;
private final AccessControlActorProvider actors;
private final AccessControlSubjects subjects;
public AccessControlComparisonOwner(AccessControlJdbcRepository repository,AccessControlActorProvider actors,AccessControlSubjects subjects){
this.repository=repository;this.actors=actors;this.subjects=subjects;
}
public List<SecurityPolicyReviewApi.Access> current(SecurityPolicyReviewApi.Actor expected,List<SecurityPolicyReviewApi.Ref> selected){
var actor=actors.current();if(actor.actorId()!=expected.user()||actor.organizationId()!=expected.department()||actor.departmentId()!=expected.department())throw denied();
var result=selected.stream().map(ref->{
var p=repository.policy(ref.id(),actor);if(p.version()!=ref.version())throw changed();
subjects.require(p.subjectType(),p.subjectRef(),actor);var purpose=p.purpose();
return new SecurityPolicyReviewApi.Access(new SecurityPolicyReviewApi.Header(p.policyId(),p.version(),p.policyName(),p.policyStatus().name()),
new NativePolicyRules.Access(p.policyId(),p.version(),p.policyStatus().name(),p.engineType().name(),p.enforcementUnit().name(),p.resourceRef(),p.subjectRef(),
p.actions().stream().map(Enum::name).toList(),p.rowConditions().stream().map(r->new NativePolicyRules.Row(r.fieldRef(),r.operator().name(),r.valueRef())).toList(),
p.columnRefs(),purpose.purposeCode(),purpose.scenarioRef(),purpose.scopeRef(),purpose.validFrom(),purpose.validUntil(),purpose.allowedActions().stream().map(Enum::name).toList()));
}).toList();
if(!actor.equals(actors.current()))throw denied();return result;
}
}
@@ -0,0 +1,127 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.log.annotation.Log;
import cn.aixunkeji.common.log.enums.BusinessType;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlApi.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/governance/v1/access-controls")
public class AccessControlController {
private final AccessControlService service;
@SaCheckPermission("aixun:governance:access-control:view")
@GetMapping("/source-candidates")
public R<List<cn.aixunkeji.datagov.governance.nativemetadata.NativeSecuritySources.Source>> sources(@RequestParam(required=false)String keyword){return R.ok(service.sources(keyword));}
@SaCheckPermission("aixun:governance:access-control:view")
@GetMapping
public R<List<PolicyView>> policies() {
return R.ok(service.policies());
}
@SaCheckPermission("aixun:governance:access-control:view")
@GetMapping("/{policyId}")
public R<PolicyView> policy(@PathVariable long policyId) {
return R.ok(service.policy(policyId));
}
@SaCheckPermission("aixun:governance:access-control:verify")
@GetMapping("/{policyId}/verifications")
public R<List<VerificationView>> verifications(@PathVariable long policyId) {
return R.ok(service.verifications(policyId));
}
@SaCheckPermission("aixun:governance:access-control:view")
@GetMapping("/subject-candidates")
public R<List<AccessControlSubjects.SubjectCandidate>> subjects(
@RequestParam SubjectType subjectType, @RequestParam(required = false) String keyword) {
return R.ok(service.subjects(subjectType, keyword));
}
@Log(title = "访问控制策略登记", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:access-control:create")
@PostMapping
public R<WriteView<PolicyView>> create(
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody CreatePolicyCommand command
) {
return R.ok(service.create(idempotencyKey, command));
}
@Log(title = "访问控制策略更新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:access-control:update")
@PutMapping("/{policyId}")
public R<WriteView<PolicyView>> update(
@PathVariable long policyId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody UpdatePolicyCommand command
) {
return R.ok(service.update(policyId, idempotencyKey, command));
}
@Log(title = "访问控制策略草稿删除", businessType = BusinessType.DELETE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:access-control:delete")
@DeleteMapping("/{policyId}")
public R<Void> delete(
@PathVariable long policyId,
@RequestParam long version,
@RequestHeader("Idempotency-Key") String idempotencyKey
) {
service.delete(policyId, version, idempotencyKey);
return R.ok();
}
@Log(title = "访问控制策略状态变更", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:access-control:status")
@PostMapping("/{policyId}/status")
public R<WriteView<PolicyView>> status(
@PathVariable long policyId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody PolicyStatusCommand command
) {
return R.ok(service.status(policyId, idempotencyKey, command));
}
@Log(title = "访问用途约束更新", businessType = BusinessType.UPDATE,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:access-control:purpose")
@PutMapping("/{policyId}/purpose")
public R<WriteView<PolicyView>> purpose(
@PathVariable long policyId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody PurposeCommand command
) {
return R.ok(service.purpose(policyId, idempotencyKey, command));
}
@Log(title = "访问控制执行证据登记", businessType = BusinessType.INSERT,
isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:access-control:enforce")
@PostMapping("/{policyId}/enforcement-evidence")
public R<WriteView<VerificationView>> evidence(
@PathVariable long policyId,
@RequestHeader("Idempotency-Key") String idempotencyKey,
@RequestBody VerificationCommand command
) {
return R.ok(service.verify(policyId, idempotencyKey, command));
}
@SaCheckPermission("aixun:governance:access-control:verify")
@GetMapping("/{policyId}/verifications/{verificationId}")
public R<VerificationView> verification(@PathVariable long policyId, @PathVariable long verificationId) {
return R.ok(service.verification(policyId, verificationId));
}
}
@@ -0,0 +1,31 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
final class AccessControlDomainException extends RuntimeException {
private final int code;
private AccessControlDomainException(int code, String message) {
super(message);
this.code = code;
}
int code() {
return code;
}
static AccessControlDomainException validation(String message) {
return new AccessControlDomainException(136240, message);
}
static AccessControlDomainException forbidden() {
return new AccessControlDomainException(136243, "无权访问该访问控制策略");
}
static AccessControlDomainException notFound() {
return new AccessControlDomainException(136244, "访问控制策略不存在或无权访问");
}
static AccessControlDomainException conflict(String message) {
return new AccessControlDomainException(136249, message);
}
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.common.core.domain.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(assignableTypes = AccessControlController.class)
class AccessControlExceptionHandler {
@ExceptionHandler(AccessControlDomainException.class)
R<Void> handle(AccessControlDomainException exception) {
return R.fail(exception.code(), exception.getMessage());
}
}
@@ -0,0 +1,505 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlApi.*;
@Repository
@RequiredArgsConstructor
class AccessControlJdbcRepository {
private static final String POLICY_SELECT = """
SELECT p.policy_id,p.policy_code,p.policy_name,p.subject_type,p.subject_ref,
t.engine_type,t.enforcement_unit,t.resource_ref,p.actions_csv,p.policy_status,
p.execution_status,p.execution_reason,p.organization_id,p.department_id,p.version,
p.create_time,p.update_time
FROM sec_access_policy p
JOIN sec_access_target t ON t.policy_id=p.policy_id AND t.organization_id=p.organization_id
AND t.department_id=p.department_id AND t.del_flag='0'
""";
private final JdbcTemplate jdbc;
List<PolicyView> policies(AccessControlActorProvider.Actor actor) {
return jdbc.query(POLICY_SELECT + """
WHERE p.organization_id=? AND p.department_id=? AND p.del_flag='0'
ORDER BY p.update_time DESC,p.policy_id DESC
""", (rs, row) -> policyView(rs, actor), actor.organizationId(), actor.departmentId());
}
PolicyView policy(long policyId, AccessControlActorProvider.Actor actor) {
return jdbc.query(POLICY_SELECT + """
WHERE p.policy_id=? AND p.organization_id=? AND p.department_id=? AND p.del_flag='0'
""", (rs, row) -> policyView(rs, actor), policyId, actor.organizationId(), actor.departmentId())
.stream().findFirst().orElseThrow(AccessControlDomainException::notFound);
}
List<PolicyView> queryPolicies(AccessControlActorProvider.Actor actor,String tableId) {
return jdbc.query(POLICY_SELECT+" WHERE p.organization_id=? AND p.department_id=? AND p.del_flag='0' "
+"AND p.policy_status<>'DRAFT' AND (t.resource_ref=? OR t.resource_ref LIKE ?) ORDER BY p.policy_id LIMIT 201",
(rs,n)->policyView(rs,actor),actor.organizationId(),actor.departmentId(),"table:"+tableId,"table:"+tableId+"/%");
}
void lockQueryPolicies(AccessControlActorProvider.Actor actor,String tableId) {
jdbc.query("SELECT p.policy_id FROM sec_access_policy p JOIN sec_access_target t ON t.policy_id=p.policy_id "
+"AND t.organization_id=p.organization_id AND t.department_id=p.department_id AND t.del_flag='0' "
+"WHERE p.organization_id=? AND p.department_id=? AND p.del_flag='0' AND (t.resource_ref=? OR t.resource_ref LIKE ?) FOR UPDATE",
(rs,n)->rs.getLong(1),actor.organizationId(),actor.departmentId(),"table:"+tableId,"table:"+tableId+"/%");
}
long create(AccessControlActorProvider.Actor actor, CreatePolicyCommand command, ExecutionStatus execution) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO sec_access_policy(
policy_id,policy_code,policy_name,subject_type,subject_ref,
actions_csv,policy_status,execution_status,execution_reason,
organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,'DRAFT',?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", id, command.policyCode(), command.policyName(), command.subjectType().name(), command.subjectRef(),
actions(command.actions()), execution.name(), execution == ExecutionStatus.UNSUPPORTED
? "UNIT_UNSUPPORTED" : null, actor.organizationId(), actor.departmentId(), actor.departmentId(),
actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) {
throw AccessControlDomainException.conflict("同部门策略编码或名称已存在");
}
replaceDetails(actor, id, command.engineType(), command.enforcementUnit(), command.resourceRef(),
command.rowConditions(), command.columnRefs(), command.purpose());
return id;
}
void update(AccessControlActorProvider.Actor actor, long policyId, UpdatePolicyCommand command,
ExecutionStatus execution) {
try {
int updated = jdbc.update("""
UPDATE sec_access_policy
SET policy_name=?,subject_type=?,subject_ref=?,actions_csv=?,execution_status=?,execution_reason=?,
update_by=?,update_time=NOW(),version=version+1
WHERE policy_id=? AND organization_id=? AND department_id=? AND policy_status='DRAFT'
AND version=? AND del_flag='0'
""", command.policyName(), command.subjectType().name(), command.subjectRef(),
actions(command.actions()), execution.name(), execution == ExecutionStatus.UNSUPPORTED
? "UNIT_UNSUPPORTED" : null, actor.actorId(), policyId, actor.organizationId(),
actor.departmentId(), command.version());
if (updated != 1) throw AccessControlDomainException.conflict("策略版本或状态已变化");
} catch (DuplicateKeyException exception) {
throw AccessControlDomainException.conflict("同部门策略名称已存在");
}
replaceDetails(actor, policyId, command.engineType(), command.enforcementUnit(), command.resourceRef(),
command.rowConditions(), command.columnRefs(), command.purpose());
}
void delete(AccessControlActorProvider.Actor actor, long policyId, long expectedVersion, String requestId,
String path, String key) {
try {
PolicyState current = lockPolicy(actor, policyId);
if (current.version() != expectedVersion) {
throw AccessControlDomainException.conflict("策略版本已变化");
}
if (current.status() != PolicyStatus.DRAFT) {
throw AccessControlDomainException.conflict("只有DRAFT策略允许删除");
}
if (current.execution() != ExecutionStatus.REGISTERED
&& current.execution() != ExecutionStatus.UNSUPPORTED) {
throw AccessControlDomainException.conflict("策略已有执行状态,拒绝删除");
}
assertDraftDeleteHistory(actor, policyId, path, requestId);
int updated = jdbc.update("""
UPDATE sec_access_policy
SET del_flag='1',update_by=?,update_time=NOW(),version=version+1
WHERE policy_id=? AND organization_id=? AND department_id=?
AND policy_status='DRAFT' AND version=? AND del_flag='0'
""", actor.actorId(), policyId, actor.organizationId(), actor.departmentId(), expectedVersion);
if (updated != 1) throw AccessControlDomainException.conflict("策略版本或状态已变化");
trail(actor, ResultType.POLICY, policyId, "DELETE", requestId, PolicyStatus.DRAFT.name(),
"DELETED", "访问控制策略草稿已删除;配置与审计记录保留");
if (completeRequest(actor, "DELETE", path, key, ResultType.POLICY, policyId) != 1) {
throw AccessControlDomainException.conflict("删除幂等请求未完成");
}
} catch (AccessControlDomainException exception) {
throw exception;
} catch (RuntimeException exception) {
throw AccessControlDomainException.conflict("访问控制策略删除前置检查未完成");
}
}
void updateStatus(AccessControlActorProvider.Actor actor, long policyId, PolicyStatus current,
PolicyStatus target, long version) {
int updated = jdbc.update("""
UPDATE sec_access_policy
SET policy_status=?,update_by=?,update_time=NOW(),version=version+1
WHERE policy_id=? AND organization_id=? AND department_id=? AND policy_status=? AND version=? AND del_flag='0'
""", target.name(), actor.actorId(), policyId, actor.organizationId(), actor.departmentId(),
current.name(), version);
if (updated != 1) throw AccessControlDomainException.conflict("策略版本或状态已变化");
}
void updatePurpose(AccessControlActorProvider.Actor actor, long policyId, PurposeCommand command) {
int updated = jdbc.update("""
UPDATE sec_access_policy SET update_by=?,update_time=NOW(),version=version+1
WHERE policy_id=? AND organization_id=? AND department_id=? AND policy_status='DRAFT'
AND version=? AND del_flag='0'
""", actor.actorId(), policyId, actor.organizationId(), actor.departmentId(), command.version());
if (updated != 1) throw AccessControlDomainException.conflict("策略版本或状态已变化");
jdbc.update("UPDATE sec_access_purpose SET del_flag='1',update_by=?,update_time=NOW(),version=version+1 "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
actor.actorId(), policyId, actor.organizationId(), actor.departmentId());
insertPurpose(actor, policyId, command.purpose());
}
long appendVerification(AccessControlActorProvider.Actor actor, PolicyView current, VerificationCommand command,
AccessControlPolicy.ExecutionAssessment assessment) {
long id = IdGeneratorUtil.nextLongId();
jdbc.update("""
INSERT INTO sec_access_verification(
verification_id,policy_id,policy_version,execution_status,reason_code,snapshot_sha256,verified_at,
organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,NOW(),?,?,?,?,NOW(),?,NOW(),'0',0)
""", id, current.policyId(), command.policyVersion(), assessment.status().name(), assessment.reasonCode(),
assessment.snapshotSha256(), actor.organizationId(), actor.departmentId(), actor.departmentId(),
actor.actorId(), actor.actorId());
for (EnforcementEvidence item : command.evidence()) {
jdbc.update("""
INSERT INTO sec_access_evidence(
evidence_id,verification_id,evidence_kind,evidence_outcome,evidence_ref,external_policy_ref,observed_at,
reliable_flag,snapshot_sha256,organization_id,department_id,create_dept,create_by,
create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), id, item.kind().name(), item.outcome().name(), item.evidenceRef(),
item.externalPolicyRef(), item.observedAt(), Boolean.TRUE.equals(item.reliable()) ? "1" : "0",
item.snapshotSha256(), actor.organizationId(), actor.departmentId(), actor.departmentId(),
actor.actorId(), actor.actorId());
}
return id;
}
void updateExecution(AccessControlActorProvider.Actor actor, long policyId, long version,
AccessControlPolicy.ExecutionAssessment assessment) {
int updated = jdbc.update("""
UPDATE sec_access_policy
SET execution_status=?,execution_reason=?,update_by=?,update_time=NOW(),version=version+1
WHERE policy_id=? AND organization_id=? AND department_id=? AND version=? AND del_flag='0'
""", assessment.status().name(), assessment.reasonCode(), actor.actorId(), policyId,
actor.organizationId(), actor.departmentId(), version);
if (updated != 1) throw AccessControlDomainException.conflict("策略版本已变化");
}
List<VerificationView> verifications(long policyId, AccessControlActorProvider.Actor actor) {
List<Long> ids = jdbc.query("SELECT verification_id FROM sec_access_verification "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0' "
+ "ORDER BY verified_at DESC,verification_id DESC LIMIT 100",
(rs, row) -> rs.getLong(1), policyId, actor.organizationId(), actor.departmentId());
return ids.stream().map(id -> verification(id, actor)).toList();
}
VerificationView verification(long verificationId, AccessControlActorProvider.Actor actor) {
return jdbc.query("""
SELECT verification_id,policy_id,policy_version,execution_status,reason_code,snapshot_sha256,verified_at
FROM sec_access_verification
WHERE verification_id=? AND organization_id=? AND department_id=? AND del_flag='0'
""", (rs, row) -> new VerificationView(rs.getLong("verification_id"), rs.getLong("policy_id"),
rs.getLong("policy_version"), ExecutionStatus.valueOf(rs.getString("execution_status")),
rs.getString("reason_code"), rs.getString("snapshot_sha256"), evidence(verificationId, actor),
rs.getObject("verified_at", LocalDateTime.class)), verificationId, actor.organizationId(),
actor.departmentId()).stream().findFirst().orElseThrow(AccessControlDomainException::notFound);
}
RequestTicket beginRequest(AccessControlActorProvider.Actor actor, String path, String key, String hash) {
return beginRequest(actor, "POST", path, key, hash);
}
RequestTicket beginRequest(AccessControlActorProvider.Actor actor, String method, String path, String key,
String hash) {
if (key == null || !key.matches("[A-Za-z0-9._:-]{16,128}")) {
throw AccessControlDomainException.validation("Idempotency-Key无效");
}
RequestRecord existing = request(actor, method, path, key);
if (existing != null) return replay(existing, hash);
String requestId = IdGeneratorUtil.nextUUID();
try {
jdbc.update("""
INSERT INTO sec_access_request(
request_record_id,request_id,actor_id,organization_id,department_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 (?,?,?,?,?,?,?,?,?,'PROCESSING',?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), requestId, actor.actorId(), actor.organizationId(),
actor.departmentId(), method, path, key, hash, actor.departmentId(), actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) {
RequestRecord raced = request(actor, method, path, key);
if (raced == null) throw AccessControlDomainException.conflict("幂等请求正在处理中");
return replay(raced, hash);
}
return new RequestTicket(requestId, null, null);
}
void completeRequest(AccessControlActorProvider.Actor actor, String path, String key,
ResultType type, long objectId) {
completeRequest(actor, "POST", path, key, type, objectId);
}
int completeRequest(AccessControlActorProvider.Actor actor, String method, String path, String key,
ResultType type, long objectId) {
return jdbc.update("""
UPDATE sec_access_request
SET request_status='COMPLETED',result_type=?,result_object_id=?,update_by=?,update_time=NOW(),version=version+1
WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method=?
AND request_path=? AND idempotency_key=? AND request_status='PROCESSING' AND del_flag='0'
""", type.name(), objectId, actor.actorId(), actor.actorId(), actor.organizationId(),
actor.departmentId(), method, path, key);
}
void failRequest(AccessControlActorProvider.Actor actor, String path, String key, String errorCode) {
failRequest(actor, "POST", path, key, errorCode);
}
void failRequest(AccessControlActorProvider.Actor actor, String method, String path, String key, String errorCode) {
jdbc.update("""
UPDATE sec_access_request SET request_status='FAILED',error_code=?,update_by=?,update_time=NOW(),version=version+1
WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method=?
AND request_path=? AND idempotency_key=? AND request_status='PROCESSING' AND del_flag='0'
""", errorCode, actor.actorId(), actor.actorId(), actor.organizationId(), actor.departmentId(),
method, path, key);
}
void trail(AccessControlActorProvider.Actor actor, ResultType objectType, long objectId, String action,
String requestId, String beforeStatus, String afterStatus, String summary) {
jdbc.update("""
INSERT INTO sec_access_trail(
trail_id,object_type,object_id,action_type,request_id,before_status,after_status,summary_text,
actor_id,organization_id,department_id,create_dept,create_by,create_time,
update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), objectType.name(), objectId, action, requestId, beforeStatus,
afterStatus, summary, actor.actorId(), actor.organizationId(), actor.departmentId(), actor.departmentId(),
actor.actorId(), actor.actorId());
}
private void replaceDetails(AccessControlActorProvider.Actor actor, long policyId, EngineType engine,
EnforcementUnit unit, String resource, List<RowCondition> rows,
List<String> columns, PurposeConstraint purpose) {
jdbc.update("UPDATE sec_access_row_condition SET del_flag='1',update_by=?,update_time=NOW(),version=version+1 "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
actor.actorId(), policyId, actor.organizationId(), actor.departmentId());
jdbc.update("UPDATE sec_access_target SET del_flag='1',update_by=?,update_time=NOW(),version=version+1 "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
actor.actorId(), policyId, actor.organizationId(), actor.departmentId());
jdbc.update("UPDATE sec_access_column_rule SET del_flag='1',update_by=?,update_time=NOW(),version=version+1 "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
actor.actorId(), policyId, actor.organizationId(), actor.departmentId());
jdbc.update("UPDATE sec_access_purpose SET del_flag='1',update_by=?,update_time=NOW(),version=version+1 "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
actor.actorId(), policyId, actor.organizationId(), actor.departmentId());
jdbc.update("""
INSERT INTO sec_access_target(
target_id,policy_id,engine_type,enforcement_unit,resource_ref,organization_id,department_id,
create_dept,create_by,create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), policyId,
engine.name(), unit.name(), resource,
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
for (RowCondition row : rows) {
jdbc.update("""
INSERT INTO sec_access_row_condition(
condition_id,policy_id,field_ref,condition_operator,value_ref,organization_id,department_id,
create_dept,create_by,create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), policyId, row.fieldRef(), row.operator().name(), row.valueRef(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
}
for (String column : columns) {
jdbc.update("""
INSERT INTO sec_access_column_rule(
column_rule_id,policy_id,column_ref,organization_id,department_id,create_dept,create_by,
create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), policyId, column, actor.organizationId(), actor.departmentId(),
actor.departmentId(), actor.actorId(), actor.actorId());
}
insertPurpose(actor, policyId, purpose);
}
private PolicyState lockPolicy(AccessControlActorProvider.Actor actor, long policyId) {
return jdbc.query("""
SELECT policy_status,execution_status,version
FROM sec_access_policy
WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0'
FOR UPDATE
""", (rs, row) -> new PolicyState(PolicyStatus.valueOf(rs.getString("policy_status")),
ExecutionStatus.valueOf(rs.getString("execution_status")), rs.getLong("version")), policyId,
actor.organizationId(), actor.departmentId()).stream().findFirst()
.orElseThrow(AccessControlDomainException::notFound);
}
private void assertDraftDeleteHistory(AccessControlActorProvider.Actor actor, long policyId, String path,
String requestId) {
List<RequestHistory> requests = jdbc.query("""
SELECT request_method,request_path,request_status,result_type,result_object_id
FROM sec_access_request
WHERE organization_id=? AND department_id=?
AND request_id<>?
AND (result_object_id=? OR request_path=? OR request_path LIKE ?)
ORDER BY create_time,request_record_id
""", (rs, row) -> new RequestHistory(rs.getString("request_method"), rs.getString("request_path"),
rs.getString("request_status"), rs.getString("result_type"),
(Long) rs.getObject("result_object_id")), actor.organizationId(), actor.departmentId(), requestId,
policyId, path, path + "/%");
if (requests.isEmpty()) throw AccessControlDomainException.conflict("策略请求历史不完整,拒绝删除");
boolean created = false;
for (RequestHistory request : requests) {
if (!"POST".equals(request.method()) || !"COMPLETED".equals(request.status())
|| request.objectId() == null || request.objectId() != policyId
|| !"POLICY".equals(request.resultType())) {
throw AccessControlDomainException.conflict("策略请求历史存在未知或未完成动作,拒绝删除");
}
if ("/".equals(request.path())) {
created = true;
} else if (!path.equals(request.path()) && !(path + "/purpose").equals(request.path())) {
throw AccessControlDomainException.conflict("策略请求历史包含状态、核验或未知动作,拒绝删除");
}
}
if (!created) throw AccessControlDomainException.conflict("策略创建请求历史缺失,拒绝删除");
List<String> actions = jdbc.query("""
SELECT action_type
FROM sec_access_trail
WHERE object_type='POLICY' AND object_id=? AND organization_id=? AND department_id=?
ORDER BY create_time,trail_id
""", (rs, row) -> rs.getString("action_type"), policyId, actor.organizationId(),
actor.departmentId());
if (actions.isEmpty() || actions.stream().filter("CREATE"::equals).count() != 1
|| actions.stream().anyMatch(action -> !Set.of("CREATE", "UPDATE", "PURPOSE").contains(action))) {
throw AccessControlDomainException.conflict("策略轨迹存在状态、核验、执行或未知动作,拒绝删除");
}
Long verificationCount = jdbc.queryForObject("""
SELECT COUNT(*) FROM sec_access_verification
WHERE policy_id=? AND organization_id=? AND department_id=?
""", Long.class, policyId, actor.organizationId(), actor.departmentId());
Long evidenceCount = jdbc.queryForObject("""
SELECT COUNT(*)
FROM sec_access_evidence e
JOIN sec_access_verification v ON v.verification_id=e.verification_id
WHERE v.policy_id=? AND v.organization_id=? AND v.department_id=?
""", Long.class, policyId, actor.organizationId(), actor.departmentId());
if (verificationCount == null || evidenceCount == null || verificationCount != 0 || evidenceCount != 0) {
throw AccessControlDomainException.conflict("策略已有核验或执行证据,拒绝删除");
}
}
private void insertPurpose(AccessControlActorProvider.Actor actor, long policyId, PurposeConstraint purpose) {
jdbc.update("""
INSERT INTO sec_access_purpose(
purpose_id,policy_id,purpose_code,scenario_ref,scope_ref,valid_from,valid_until,allowed_actions_csv,
organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), policyId, purpose.purposeCode(), purpose.scenarioRef(), purpose.scopeRef(),
purpose.validFrom(), purpose.validUntil(), actions(purpose.allowedActions()), actor.organizationId(),
actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
}
private PolicyView policyView(ResultSet rs, AccessControlActorProvider.Actor actor) throws SQLException {
long id = rs.getLong("policy_id");
return new PolicyView(id, rs.getString("policy_code"), rs.getString("policy_name"),
SubjectType.valueOf(rs.getString("subject_type")), rs.getString("subject_ref"),
EngineType.valueOf(rs.getString("engine_type")), EnforcementUnit.valueOf(rs.getString("enforcement_unit")),
rs.getString("resource_ref"), parseActions(rs.getString("actions_csv")), rows(id, actor), columns(id, actor),
purpose(id, actor), PolicyStatus.valueOf(rs.getString("policy_status")),
ExecutionStatus.valueOf(rs.getString("execution_status")), rs.getString("execution_reason"),
rs.getLong("organization_id"), rs.getLong("department_id"), rs.getLong("version"),
rs.getObject("create_time", LocalDateTime.class), rs.getObject("update_time", LocalDateTime.class));
}
private List<RowCondition> rows(long id, AccessControlActorProvider.Actor actor) {
return jdbc.query("SELECT field_ref,condition_operator,value_ref FROM sec_access_row_condition "
+ "WHERE policy_id=? AND organization_id=? AND department_id=? AND del_flag='0' ORDER BY condition_id",
(rs, row) -> new RowCondition(rs.getString("field_ref"),
RowOperator.valueOf(rs.getString("condition_operator")), rs.getString("value_ref")),
id, actor.organizationId(), actor.departmentId());
}
private List<String> columns(long id, AccessControlActorProvider.Actor actor) {
return jdbc.query("SELECT column_ref FROM sec_access_column_rule WHERE policy_id=? AND organization_id=? "
+ "AND department_id=? AND del_flag='0' ORDER BY column_rule_id", (rs, row) -> rs.getString("column_ref"),
id, actor.organizationId(), actor.departmentId());
}
private PurposeConstraint purpose(long id, AccessControlActorProvider.Actor actor) {
return jdbc.query("SELECT purpose_code,scenario_ref,scope_ref,valid_from,valid_until,allowed_actions_csv "
+ "FROM sec_access_purpose WHERE policy_id=? AND organization_id=? AND department_id=? "
+ "AND del_flag='0' ORDER BY purpose_id DESC LIMIT 1", (rs, row) -> new PurposeConstraint(
rs.getString("purpose_code"), rs.getString("scenario_ref"), rs.getString("scope_ref"),
rs.getObject("valid_from", LocalDateTime.class), rs.getObject("valid_until", LocalDateTime.class),
parseActions(rs.getString("allowed_actions_csv"))), id, actor.organizationId(), actor.departmentId())
.stream().findFirst().orElseThrow(AccessControlDomainException::notFound);
}
private List<EnforcementEvidence> evidence(long id, AccessControlActorProvider.Actor actor) {
return jdbc.query("SELECT evidence_kind,evidence_outcome,evidence_ref,external_policy_ref,observed_at,reliable_flag,snapshot_sha256 "
+ "FROM sec_access_evidence WHERE verification_id=? AND organization_id=? AND department_id=? "
+ "AND del_flag='0' ORDER BY evidence_id", (rs, row) -> new EnforcementEvidence(
EvidenceKind.valueOf(rs.getString("evidence_kind")),
EvidenceOutcome.valueOf(rs.getString("evidence_outcome")), rs.getString("evidence_ref"),
rs.getString("external_policy_ref"), rs.getObject("observed_at", LocalDateTime.class),
"1".equals(rs.getString("reliable_flag")), rs.getString("snapshot_sha256")),
id, actor.organizationId(), actor.departmentId());
}
private RequestRecord request(AccessControlActorProvider.Actor actor, String path, String key) {
return jdbc.query("SELECT request_id,request_sha256,request_status,result_type,result_object_id "
+ "FROM sec_access_request WHERE actor_id=? AND organization_id=? AND department_id=? "
+ "AND request_method='POST' AND request_path=? AND idempotency_key=? AND del_flag='0'",
(rs, row) -> new RequestRecord(rs.getString("request_id"), rs.getString("request_sha256"),
rs.getString("request_status"), rs.getString("result_type"), (Long) rs.getObject("result_object_id")),
actor.actorId(), actor.organizationId(), actor.departmentId(), path, key)
.stream().findFirst().orElse(null);
}
private RequestRecord request(AccessControlActorProvider.Actor actor, String method, String path, String key) {
if ("POST".equals(method)) return request(actor, path, key);
return jdbc.query("SELECT request_id,request_sha256,request_status,result_type,result_object_id "
+ "FROM sec_access_request WHERE actor_id=? AND organization_id=? AND department_id=? "
+ "AND request_method=? AND request_path=? AND idempotency_key=? AND del_flag='0'",
(rs, row) -> new RequestRecord(rs.getString("request_id"), rs.getString("request_sha256"),
rs.getString("request_status"), rs.getString("result_type"), (Long) rs.getObject("result_object_id")),
actor.actorId(), actor.organizationId(), actor.departmentId(), method, path, key)
.stream().findFirst().orElse(null);
}
private static RequestTicket replay(RequestRecord record, String hash) {
if (!record.hash().equals(hash)) throw AccessControlDomainException.conflict("同一幂等键不能用于不同请求");
if (!"COMPLETED".equals(record.status()) || record.resultType() == null || record.objectId() == null) {
throw AccessControlDomainException.conflict("幂等请求尚未形成可回放结果");
}
return new RequestTicket(record.requestId(), ResultType.valueOf(record.resultType()), record.objectId());
}
private static String actions(List<AccessAction> values) {
return values.stream().map(Enum::name).sorted().reduce((left, right) -> left + "," + right).orElseThrow();
}
private static List<AccessAction> parseActions(String value) {
return Arrays.stream(value.split(",")).map(AccessAction::valueOf).toList();
}
enum ResultType { POLICY, VERIFICATION }
record RequestTicket(String requestId, ResultType replayType, Long replayId) { }
private record PolicyState(PolicyStatus status, ExecutionStatus execution, long version) { }
private record RequestHistory(String method, String path, String status, String resultType, Long objectId) { }
private record RequestRecord(String requestId, String hash, String status, String resultType, Long objectId) { }
}
@@ -0,0 +1,297 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Clock;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlApi.*;
@Component
class AccessControlPolicy {
private static final Pattern CODE = Pattern.compile("[A-Z][A-Z0-9_]{1,63}");
private static final Pattern SUBJECT_REF = Pattern.compile("[A-Za-z0-9._:-]{1,128}");
private static final Pattern RESOURCE_REF = Pattern.compile("[A-Za-z0-9._:/-]{1,512}");
private static final Pattern EVIDENCE_REF = Pattern.compile("[A-Za-z0-9._:/-]{1,512}");
private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
private static final Pattern SQL_OR_SCRIPT = Pattern.compile(
"(?i)(select\\s|insert\\s|update\\s|delete\\s|drop\\s|truncate\\s|merge\\s|union\\s|where\\s|"
+ "script|javascript:|https?://|file:|jdbc:|secret(ref)?\\s*[:=]|\\$\\{|;|--|/\\*|\\(|\\))");
private static final Set<EnforcementUnit> SUPPORTED = EnumSet.of(
EnforcementUnit.PLATFORM_QUERY,
EnforcementUnit.HIVE_TABLE_SELECT,
EnforcementUnit.HIVE_PROTECTED_EXPORT,
EnforcementUnit.DORIS_TENANT_ROW_POLICY,
EnforcementUnit.DORIS_COLUMN_SELECT);
private final JsonMapper jsonMapper;
private final Clock clock;
@Autowired
AccessControlPolicy(JsonMapper jsonMapper) {
this(jsonMapper, Clock.systemDefaultZone());
}
AccessControlPolicy(JsonMapper jsonMapper, Clock clock) {
this.jsonMapper = jsonMapper;
this.clock = clock;
}
CreatePolicyCommand normalize(CreatePolicyCommand value) {
if (value == null) throw AccessControlDomainException.validation("访问控制策略不能为空");
return new CreatePolicyCommand(code(value.policyCode(), "策略编码"), text(value.policyName(), 100, "策略名称"),
required(value.subjectType(), "主体类型"), subjectRef(value.subjectRef()),
required(value.engineType(), "执行引擎"), required(value.enforcementUnit(), "执行单元"),
resourceRef(value.resourceRef()), actions(value.actions()), rowConditions(value.rowConditions()),
columnRefs(value.columnRefs()), purpose(value.purpose()));
}
UpdatePolicyCommand normalize(UpdatePolicyCommand value) {
if (value == null) throw AccessControlDomainException.validation("访问控制策略不能为空");
return new UpdatePolicyCommand(text(value.policyName(), 100, "策略名称"),
required(value.subjectType(), "主体类型"), subjectRef(value.subjectRef()),
required(value.engineType(), "执行引擎"), required(value.enforcementUnit(), "执行单元"),
resourceRef(value.resourceRef()), actions(value.actions()), rowConditions(value.rowConditions()),
columnRefs(value.columnRefs()), purpose(value.purpose()), version(value.version()));
}
PolicyStatusCommand normalize(PolicyStatusCommand value) {
if (value == null || value.targetStatus() == null) {
throw AccessControlDomainException.validation("目标状态不能为空");
}
return new PolicyStatusCommand(value.targetStatus(), text(value.reason(), 500, "状态原因"),
version(value.version()));
}
PurposeCommand normalize(PurposeCommand value) {
if (value == null) throw AccessControlDomainException.validation("用途约束不能为空");
return new PurposeCommand(purpose(value.purpose()), version(value.version()));
}
VerificationCommand normalize(VerificationCommand value) {
if (value == null || value.evidence() == null) {
throw AccessControlDomainException.validation("执行验证证据不能为空");
}
if (value.evidence().size() > EvidenceKind.values().length) {
throw AccessControlDomainException.validation("执行验证证据存在重复项");
}
List<EnforcementEvidence> evidence = new ArrayList<>(value.evidence().size());
Set<EvidenceKind> kinds = new HashSet<>();
for (EnforcementEvidence item : value.evidence()) {
if (item == null || item.kind() == null || item.outcome() == null || !kinds.add(item.kind())) {
throw AccessControlDomainException.validation("执行验证证据类型无效或重复");
}
evidence.add(new EnforcementEvidence(item.kind(), item.outcome(), evidenceRef(item.evidenceRef()),
evidenceRef(item.externalPolicyRef()), required(item.observedAt(), "证据时间"), item.reliable(),
sha(item.snapshotSha256())));
}
return new VerificationCommand(version(value.policyVersion()), List.copyOf(evidence));
}
void requireTransition(PolicyStatus current, PolicyStatus target) {
boolean valid = switch (current) {
case DRAFT -> target == PolicyStatus.ACTIVE || target == PolicyStatus.ARCHIVED;
case ACTIVE -> target == PolicyStatus.DEPRECATED;
case DEPRECATED -> target == PolicyStatus.ARCHIVED;
case ARCHIVED -> false;
};
if (!valid) throw AccessControlDomainException.conflict("策略状态流转无效");
}
void requireCompatible(EngineType engine, EnforcementUnit unit, List<AccessAction> actions,
List<RowCondition> rows, List<String> columns) {
if(unit==EnforcementUnit.PLATFORM_QUERY) {
if(columns.isEmpty())throw AccessControlDomainException.validation("平台查询策略必须明确选择授权字段");
return;
}
if ((engine == EngineType.HIVE) != unit.name().startsWith("HIVE_")) {
throw AccessControlDomainException.validation("执行引擎与执行单元不匹配");
}
if (unit == EnforcementUnit.HIVE_PROTECTED_EXPORT && !actions.contains(AccessAction.EXPORT)) {
throw AccessControlDomainException.validation("Hive受保护表导出单元必须包含EXPORT动作");
}
if (unit == EnforcementUnit.DORIS_TENANT_ROW_POLICY && rows.isEmpty()) {
throw AccessControlDomainException.validation("Doris租户行策略必须包含结构化行条件");
}
if (unit == EnforcementUnit.DORIS_COLUMN_SELECT && columns.isEmpty()) {
throw AccessControlDomainException.validation("Doris列SELECT必须包含列引用");
}
}
boolean supported(EnforcementUnit unit) {
return SUPPORTED.contains(unit);
}
ExecutionAssessment assess(EnforcementUnit unit, List<EnforcementEvidence> evidence) {
if (!supported(unit)) return new ExecutionAssessment(ExecutionStatus.UNSUPPORTED, "UNIT_UNSUPPORTED", null);
Map<EvidenceKind, EnforcementEvidence> byKind = new EnumMap<>(EvidenceKind.class);
evidence.forEach(item -> byKind.put(item.kind(), item));
if (byKind.size() != EvidenceKind.values().length) {
return new ExecutionAssessment(ExecutionStatus.NOT_ENFORCED, "EVIDENCE_INCOMPLETE", null);
}
if (byKind.values().stream().anyMatch(item -> !Boolean.TRUE.equals(item.reliable()))) {
return new ExecutionAssessment(ExecutionStatus.NOT_ENFORCED, "EVIDENCE_UNRELIABLE", null);
}
if (byKind.get(EvidenceKind.DISPATCH).outcome() != EvidenceOutcome.DISPATCHED
|| byKind.get(EvidenceKind.READBACK).outcome() != EvidenceOutcome.MATCHED
|| byKind.get(EvidenceKind.ALLOW).outcome() != EvidenceOutcome.ALLOWED
|| byKind.get(EvidenceKind.DENY).outcome() != EvidenceOutcome.DENIED) {
return new ExecutionAssessment(ExecutionStatus.NOT_ENFORCED, "EVIDENCE_OUTCOME_MISMATCH", null);
}
LocalDateTime now = LocalDateTime.now(clock);
if (byKind.values().stream().anyMatch(item -> item.observedAt().isAfter(now.plusMinutes(5)))) {
return new ExecutionAssessment(ExecutionStatus.NOT_ENFORCED, "EVIDENCE_TIME_INVALID", null);
}
String sha = byKind.get(EvidenceKind.DISPATCH).snapshotSha256();
if (byKind.values().stream().anyMatch(item -> !sha.equals(item.snapshotSha256()))) {
return new ExecutionAssessment(ExecutionStatus.NOT_ENFORCED, "EVIDENCE_SHA_MISMATCH", null);
}
String externalPolicyRef = byKind.get(EvidenceKind.DISPATCH).externalPolicyRef();
if (byKind.values().stream().anyMatch(item -> !externalPolicyRef.equals(item.externalPolicyRef()))) {
return new ExecutionAssessment(ExecutionStatus.NOT_ENFORCED, "EXTERNAL_POLICY_MISMATCH", null);
}
return new ExecutionAssessment(ExecutionStatus.ENFORCED, null, sha);
}
String requestHash(Object value) {
try {
return digest(jsonMapper.writeValueAsString(value));
} catch (Exception exception) {
throw new IllegalStateException("JSON序列化失败", exception);
}
}
String deleteHash(long policyId, long expectedVersion, long actorId, long organizationId, long departmentId,
String method, String path, String idempotencyKey) {
return requestHash(List.of(method, path, idempotencyKey, policyId, expectedVersion,
actorId, organizationId, departmentId));
}
private PurposeConstraint purpose(PurposeConstraint value) {
if (value == null) throw AccessControlDomainException.validation("用途约束不能为空");
LocalDateTime from = required(value.validFrom(), "用途开始时间");
LocalDateTime until = required(value.validUntil(), "用途结束时间");
if (!until.isAfter(from)) throw AccessControlDomainException.validation("用途结束时间必须晚于开始时间");
List<AccessAction> allowed = actions(value.allowedActions());
return new PurposeConstraint(code(value.purposeCode(), "用途编码"),
resourceRef(value.scenarioRef()), resourceRef(value.scopeRef()), from, until, allowed);
}
private List<RowCondition> rowConditions(List<RowCondition> values) {
if (values == null) return List.of();
if (values.size() > 20) throw AccessControlDomainException.validation("结构化行条件超过上限");
List<RowCondition> result = new ArrayList<>(values.size());
for (RowCondition value : values) {
if (value == null || value.operator() == null) {
throw AccessControlDomainException.validation("结构化行条件无效");
}
String valueRef = switch (value.operator()) {
case IS_NULL, IS_NOT_NULL -> value.valueRef() == null || value.valueRef().isBlank()
? null : safeValueRef(value.valueRef());
default -> safeValueRef(value.valueRef());
};
result.add(new RowCondition(resourceRef(value.fieldRef()), value.operator(), valueRef));
}
return List.copyOf(result);
}
private List<String> columnRefs(List<String> values) {
if (values == null) return List.of();
if (values.size() > 200) throw AccessControlDomainException.validation("列引用超过上限");
return values.stream().map(AccessControlPolicy::resourceRef).distinct().toList();
}
private List<AccessAction> actions(List<AccessAction> values) {
if (values == null || values.isEmpty()) throw AccessControlDomainException.validation("允许动作不能为空");
return values.stream().map(value -> required(value, "允许动作")).distinct().toList();
}
private static String safeValueRef(String value) {
String result = text(value, 256, "条件值引用");
if (SQL_OR_SCRIPT.matcher(result).find()) {
throw AccessControlDomainException.validation("行条件只允许结构化值引用,不接受SQL或脚本");
}
return result;
}
private static String code(String value, String label) {
String result = text(value, 64, label).toUpperCase(Locale.ROOT);
if (!CODE.matcher(result).matches()) throw AccessControlDomainException.validation(label + "格式无效");
return result;
}
private static String subjectRef(String value) {
String result = text(value, 128, "主体引用");
if (!SUBJECT_REF.matcher(result).matches()) {
throw AccessControlDomainException.validation("主体引用格式无效");
}
return result;
}
private static String resourceRef(String value) {
String result = text(value, 512, "资源引用");
if (!RESOURCE_REF.matcher(result).matches()) {
throw AccessControlDomainException.validation("资源引用格式无效");
}
return result;
}
private static String evidenceRef(String value) {
String result = text(value, 512, "证据引用");
if (!EVIDENCE_REF.matcher(result).matches()) {
throw AccessControlDomainException.validation("证据引用格式无效");
}
return result;
}
private static String sha(String value) {
String result = text(value, 64, "证据SHA").toLowerCase(Locale.ROOT);
if (!SHA256.matcher(result).matches()) throw AccessControlDomainException.validation("证据SHA格式无效");
return result;
}
private static long version(Long value) {
if (value == null || value < 0) throw AccessControlDomainException.validation("版本无效");
return value;
}
private static <T> T required(T value, String label) {
if (value == null) throw AccessControlDomainException.validation(label + "不能为空");
return value;
}
private static String text(String value, int max, String label) {
if (value == null || value.isBlank()) throw AccessControlDomainException.validation(label + "不能为空");
String result = value.trim();
if (result.length() > max || result.contains("\n") || result.contains("\r") || result.indexOf('\0') >= 0) {
throw AccessControlDomainException.validation(label + "格式无效");
}
return result;
}
private static String digest(String value) {
try {
byte[] bytes = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
return HexFormat.of().formatHex(bytes);
} catch (Exception exception) {
throw new IllegalStateException("SHA-256不可用", exception);
}
}
record ExecutionAssessment(ExecutionStatus status, String reasonCode, String snapshotSha256) { }
}
@@ -0,0 +1,35 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.datagov.governance.securityquery.NativePolicyRules;
import cn.aixunkeji.datagov.governance.api.nativemetadata.NativeQueryPolicyApi;
import org.springframework.stereotype.Component;
import java.util.List;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlApi.*;
@Component
public class AccessControlQueryPolicies {
private final AccessControlJdbcRepository repository;
public AccessControlQueryPolicies(AccessControlJdbcRepository repository){this.repository=repository;}
public void lock(long user,long department,String tableId){repository.lockQueryPolicies(new AccessControlActorProvider.Actor(user,department,department),tableId);}
public List<NativePolicyRules.Access> read(long user,long department,String tableId){
return repository.queryPolicies(new AccessControlActorProvider.Actor(user,department,department),tableId).stream().map(p->{
var purpose=p.purpose();return new NativePolicyRules.Access(p.policyId(),p.version(),p.policyStatus().name(),p.engineType().name(),
p.enforcementUnit().name(),p.resourceRef(),p.subjectRef(),p.actions().stream().map(Enum::name).toList(),
p.rowConditions().stream().map(r->new NativePolicyRules.Row(r.fieldRef(),r.operator().name(),r.valueRef())).toList(),p.columnRefs(),
purpose.purposeCode(),purpose.scenarioRef(),purpose.scopeRef(),purpose.validFrom(),purpose.validUntil(),purpose.allowedActions().stream().map(Enum::name).toList());
}).toList();
}
/** Invoked only after the native query gateway has completed and the owner revalidated all versions. */
public void record(long user,long department,NativeQueryPolicyApi.Version version,NativeQueryPolicyApi.Completion query){
var actor=new AccessControlActorProvider.Actor(user,department,department);var current=repository.policy(version.policyId(),actor);
if(current.version()!=version.version()||current.policyStatus()!=PolicyStatus.ACTIVE||current.enforcementUnit()!=EnforcementUnit.PLATFORM_QUERY)throw NativePolicyRules.denied();
var evidence=List.of(new EnforcementEvidence(EvidenceKind.READBACK,EvidenceOutcome.MATCHED,"native-query:"+query.queryId(),
"platform-query:"+current.policyId()+":"+version.version(),query.observedAt(),true,query.querySha256()),
new EnforcementEvidence(EvidenceKind.ALLOW,EvidenceOutcome.ALLOWED,"native-result:"+query.queryId(),
"platform-query:"+current.policyId()+":"+version.version(),query.observedAt(),true,query.fingerprint()));
var assessment=new AccessControlPolicy.ExecutionAssessment(ExecutionStatus.ENFORCED,"PLATFORM_QUERY_ONLY",query.fingerprint());
repository.appendVerification(actor,current,new VerificationCommand(version.version(),evidence),assessment);
if(current.executionStatus()!=ExecutionStatus.ENFORCED||!"PLATFORM_QUERY_ONLY".equals(current.executionReason()))
repository.updateExecution(actor,current.policyId(),current.version(),assessment);
}
}
@@ -0,0 +1,262 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.List;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlApi.*;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlJdbcRepository.ResultType;
@Service
@RequiredArgsConstructor
class AccessControlService {
private final AccessControlJdbcRepository repository;
private final AccessControlPolicy policy;
private final AccessControlActorProvider actors;
private final TransactionTemplate transactions;
private final AccessControlSubjects subjects;
@org.springframework.beans.factory.annotation.Autowired
private cn.aixunkeji.datagov.governance.nativemetadata.NativeSecuritySources sources;
List<cn.aixunkeji.datagov.governance.nativemetadata.NativeSecuritySources.Source> sources(String keyword) {
var actor=actors.current();return sources.search(actor.actorId(),actor.departmentId(),keyword);
}
List<AccessControlSubjects.SubjectCandidate> subjects(SubjectType type, String keyword) {
return subjects.search(type, keyword, actors.current());
}
List<PolicyView> policies() {
return repository.policies(actors.current());
}
PolicyView policy(long policyId) {
return repository.policy(policyId, actors.current());
}
VerificationView verification(long policyId, long verificationId) {
var actor = actors.current();
repository.policy(policyId, actor);
var result = repository.verification(verificationId, actor);
if (result.policyId() != policyId) throw AccessControlDomainException.notFound();
return result;
}
WriteView<PolicyView> create(String key, CreatePolicyCommand raw) {
CreatePolicyCommand command = policy.normalize(raw);
policy.requireCompatible(command.engineType(), command.enforcementUnit(), command.actions(),
command.rowConditions(), command.columnRefs());
return policyWrite("/", key, command, "POLICY_CREATE", (actor, requestId) -> {
subjects.require(command.subjectType(), command.subjectRef(), actor);
requirePlatformPolicy(actor,command.engineType(),command.enforcementUnit(),command.resourceRef(),command.rowConditions(),command.columnRefs(),command.purpose());
ExecutionStatus execution = policy.supported(command.enforcementUnit())
? ExecutionStatus.REGISTERED : ExecutionStatus.UNSUPPORTED;
long id = repository.create(actor, command, execution);
repository.trail(actor, ResultType.POLICY, id, "CREATE", requestId, null, execution.name(),
execution == ExecutionStatus.UNSUPPORTED ? "执行单元固定不支持" : "策略已登记;不代表外部控制已生效");
return id;
});
}
WriteView<PolicyView> update(long policyId, String key, UpdatePolicyCommand raw) {
UpdatePolicyCommand command = policy.normalize(raw);
policy.requireCompatible(command.engineType(), command.enforcementUnit(), command.actions(),
command.rowConditions(), command.columnRefs());
return policyWrite("/" + policyId, key, command, "POLICY_UPDATE", (actor, requestId) -> {
PolicyView current = repository.policy(policyId, actor);
requireVersion(current, command.version());
if (current.policyStatus() != PolicyStatus.DRAFT) {
throw AccessControlDomainException.conflict("只有DRAFT策略允许修改");
}
subjects.require(command.subjectType(), command.subjectRef(), actor);
requirePlatformPolicy(actor,command.engineType(),command.enforcementUnit(),command.resourceRef(),command.rowConditions(),command.columnRefs(),command.purpose());
ExecutionStatus execution = policy.supported(command.enforcementUnit())
? ExecutionStatus.REGISTERED : ExecutionStatus.UNSUPPORTED;
repository.update(actor, policyId, command, execution);
repository.trail(actor, ResultType.POLICY, policyId, "UPDATE", requestId,
current.executionStatus().name(), execution.name(), "策略登记内容已更新;原执行证据不继承");
return policyId;
});
}
void delete(long policyId, long expectedVersion, String key) {
if (policyId <= 0 || expectedVersion < 0) {
throw AccessControlDomainException.validation("策略或版本无效");
}
if (key == null || !key.matches("[A-Za-z0-9._:-]{16,128}")) {
throw AccessControlDomainException.validation("Idempotency-Key无效");
}
var actor = actors.current();
String path = "/" + policyId;
String hash = policy.deleteHash(policyId, expectedVersion, actor.actorId(), actor.organizationId(), actor.departmentId(),
"DELETE", path, key);
var ticket = begin(actor, "DELETE", path, key, hash);
if (ticket.replayType() != null) {
requireReplay(ticket, ResultType.POLICY);
return;
}
try {
Integer completed = transactions.execute(status -> {
repository.delete(actor, policyId, expectedVersion, ticket.requestId(), path, key);
return 1;
});
if (completed == null) throw AccessControlDomainException.conflict("策略删除请求未完成");
} catch (RuntimeException exception) {
fail(actor, "DELETE", path, key, exception);
throw exception;
}
}
WriteView<PolicyView> status(long policyId, String key, PolicyStatusCommand raw) {
PolicyStatusCommand command = policy.normalize(raw);
return policyWrite("/" + policyId + "/status", key, command, "POLICY_STATUS", (actor, requestId) -> {
PolicyView current = repository.policy(policyId, actor);
requireVersion(current, command.version());
policy.requireTransition(current.policyStatus(), command.targetStatus());
if(command.targetStatus()==PolicyStatus.ACTIVE)requirePlatformPolicy(actor,current.engineType(),current.enforcementUnit(),current.resourceRef(),current.rowConditions(),current.columnRefs(),current.purpose());
repository.updateStatus(actor, policyId, current.policyStatus(), command.targetStatus(), command.version());
repository.trail(actor, ResultType.POLICY, policyId, "STATUS", requestId,
current.policyStatus().name(), command.targetStatus().name(), command.reason());
return policyId;
});
}
WriteView<PolicyView> purpose(long policyId, String key, PurposeCommand raw) {
PurposeCommand command = policy.normalize(raw);
return policyWrite("/" + policyId + "/purpose", key, command, "PURPOSE_UPDATE", (actor, requestId) -> {
PolicyView current = repository.policy(policyId, actor);
requireVersion(current, command.version());
if (current.policyStatus() != PolicyStatus.DRAFT) {
throw AccessControlDomainException.conflict("只有DRAFT策略允许修改用途约束");
}
requirePlatformPolicy(actor,current.engineType(),current.enforcementUnit(),current.resourceRef(),current.rowConditions(),current.columnRefs(),command.purpose());
repository.updatePurpose(actor, policyId, command);
repository.trail(actor, ResultType.POLICY, policyId, "PURPOSE", requestId,
current.policyStatus().name(), current.policyStatus().name(), "用途约束已更新");
return policyId;
});
}
WriteView<VerificationView> verify(long policyId, String key, VerificationCommand raw) {
VerificationCommand command = policy.normalize(raw);
var actor = actors.current();
String path = "/" + policyId + "/enforcement-evidence";
var ticket = begin(actor, path, key, policy.requestHash(command));
if (ticket.replayType() != null) {
requireReplay(ticket, ResultType.VERIFICATION);
return new WriteView<>(ticket.requestId(), repository.verification(ticket.replayId(), actor));
}
try {
Long id = transactions.execute(status -> {
PolicyView current = repository.policy(policyId, actor);
requireVersion(current, command.policyVersion());
if (current.policyStatus() != PolicyStatus.ACTIVE) {
throw AccessControlDomainException.conflict("只有ACTIVE策略允许验证执行证据");
}
requireTrustedSource();
var assessment = policy.assess(current.enforcementUnit(), command.evidence());
long verificationId = repository.appendVerification(actor, current, command, assessment);
repository.updateExecution(actor, policyId, command.policyVersion(), assessment);
repository.trail(actor, ResultType.VERIFICATION, verificationId, "VERIFY", ticket.requestId(),
current.executionStatus().name(), assessment.status().name(),
assessment.reasonCode() == null ? "四项可靠一致证据完整" : assessment.reasonCode());
repository.completeRequest(actor, path, key, ResultType.VERIFICATION, verificationId);
return verificationId;
});
if (id == null) throw AccessControlDomainException.conflict("执行验证请求未完成");
return new WriteView<>(ticket.requestId(), repository.verification(id, actor));
} catch (RuntimeException exception) {
fail(actor, path, key, exception);
throw exception;
}
}
private WriteView<PolicyView> policyWrite(String path, String key, Object command, String action,
PolicyMutation mutation) {
var actor = actors.current();
var ticket = begin(actor, path, key, policy.requestHash(command));
if (ticket.replayType() != null) {
requireReplay(ticket, ResultType.POLICY);
return new WriteView<>(ticket.requestId(), repository.policy(ticket.replayId(), actor));
}
try {
Long id = transactions.execute(status -> {
long result = mutation.run(actor, ticket.requestId());
repository.completeRequest(actor, path, key, ResultType.POLICY, result);
return result;
});
if (id == null) throw AccessControlDomainException.conflict(action + "未完成");
return new WriteView<>(ticket.requestId(), repository.policy(id, actor));
} catch (RuntimeException exception) {
fail(actor, path, key, exception);
throw exception;
}
}
private AccessControlJdbcRepository.RequestTicket begin(AccessControlActorProvider.Actor actor,
String path, String key, String hash) {
var ticket = transactions.execute(status -> repository.beginRequest(actor, path, key, hash));
if (ticket == null) throw AccessControlDomainException.conflict("幂等请求未建立");
return ticket;
}
private AccessControlJdbcRepository.RequestTicket begin(AccessControlActorProvider.Actor actor, String method,
String path, String key, String hash) {
var ticket = transactions.execute(status -> repository.beginRequest(actor, method, path, key, hash));
if (ticket == null) throw AccessControlDomainException.conflict("幂等请求未建立");
return ticket;
}
private void fail(AccessControlActorProvider.Actor actor, String path, String key, RuntimeException exception) {
fail(actor, "POST", path, key, exception);
}
private void fail(AccessControlActorProvider.Actor actor, String method, String path, String key,
RuntimeException exception) {
transactions.executeWithoutResult(status -> repository.failRequest(actor, method, path, key,
exception instanceof AccessControlDomainException domain ? Integer.toString(domain.code()) : "136299"));
}
private static void requireVersion(PolicyView current, long version) {
if (current.version() != version) throw AccessControlDomainException.conflict("策略版本已变化");
}
private void requirePlatformPolicy(AccessControlActorProvider.Actor actor,EngineType engine,EnforcementUnit unit,
String reference,List<RowCondition> rows,List<String> columns,PurposeConstraint purpose) {
if(sources==null)requireTrustedSource();
if(unit!=EnforcementUnit.PLATFORM_QUERY)throw AccessControlDomainException.validation("当前仅支持平台查询执行单元;外部数据库策略下发尚未开放");
if(purpose==null||!java.util.Set.of("BI_QUERY","API_QUERY").contains(purpose.purposeCode())||!"NATIVE_QUERY".equals(purpose.scenarioRef())||!reference.equals(purpose.scopeRef()))
throw AccessControlDomainException.validation("平台查询用途须绑定BI_QUERY或API_QUERY、NATIVE_QUERY和当前版本资源");
var refs=new java.util.HashSet<String>(columns);rows.forEach(row->refs.add(row.fieldRef()));
try {
var source="API_QUERY".equals(purpose.purposeCode())?sources.requireApiGrant(actor.actorId(),actor.departmentId(),reference,List.copyOf(refs))
:sources.require(actor.actorId(),actor.departmentId(),reference,List.copyOf(refs));
if(!source.engineType().equals(engine.name())||columns.isEmpty())throw new IllegalArgumentException();
if(source.fields().stream().anyMatch(field->field.restricted()&&refs.contains(field.reference())))throw new IllegalArgumentException();
} catch(RuntimeException invalid){throw AccessControlDomainException.validation("来源、字段或扫描版本已变化,或字段仍受限制,请重新选择");}
}
// A client-written evidence form cannot attest to actual query execution.
private static void requireTrustedSource() {
throw AccessControlDomainException.validation("当前没有可用的可信候选,请联系管理员");
}
List<VerificationView> verifications(long policyId) {
var actor = actors.current();
repository.policy(policyId, actor);
return repository.verifications(policyId, actor);
}
private static void requireReplay(AccessControlJdbcRepository.RequestTicket ticket, ResultType expected) {
if (ticket.replayType() != expected || ticket.replayId() == null) {
throw AccessControlDomainException.conflict("幂等回放结果类型不匹配");
}
}
private interface PolicyMutation {
long run(AccessControlActorProvider.Actor actor, String requestId);
}
}
@@ -0,0 +1,77 @@
package cn.aixunkeji.datagov.governance.accesscontrol;
import cn.aixunkeji.system.api.RemoteUserService;
import cn.aixunkeji.system.api.RemoteRoleService;
import cn.aixunkeji.system.api.RemoteDeptService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Objects;
import static cn.aixunkeji.datagov.governance.accesscontrol.AccessControlApi.*;
/** FR-SEC-0212: only existing public RCP6 scoped identity contracts. */
@Component
class AccessControlSubjects {
@DubboReference(check = false, timeout = 5000, retries = 0)
private RemoteUserService users;
@DubboReference(check = false, timeout = 5000, retries = 0)
private RemoteRoleService roles;
@DubboReference(check = false, timeout = 5000, retries = 0)
private RemoteDeptService departments;
List<SubjectCandidate> search(SubjectType type, String keyword, AccessControlActorProvider.Actor actor) {
if (type == null) throw AccessControlDomainException.validation("请选择主体类型");
String text = keyword == null ? "" : keyword.trim();
if (text.length() > 100) throw AccessControlDomainException.validation("搜索内容过长");
if (type == SubjectType.USER && text.length() < 2) return List.of();
try {
if (type == SubjectType.DEPARTMENT) {
return departments.selectDeptsByList().stream()
.filter(d -> Objects.equals(d.getDeptId(), actor.departmentId())
&& d.getDeptName() != null && d.getDeptName().contains(text))
.map(d -> new SubjectCandidate("DEPARTMENT:" + d.getDeptId(), type, d.getDeptName())).toList();
}
if (type == SubjectType.USER) {
return users.searchActiveUsersByDept(actor.departmentId(), text, 20).stream()
.filter(u -> u.userId() != null && u.userId() > 0 && Objects.equals(u.deptId(), actor.departmentId())
&& "0".equals(u.status()))
.limit(20).map(u -> new SubjectCandidate("USER:" + u.userId(), type,
u.nickName() == null || u.nickName().isBlank() ? u.userName() : u.nickName())).toList();
}
return roles.searchActiveRolesByDept(actor.departmentId(), text, 20).stream()
.filter(r -> r.getRoleId() != null && r.getRoleId() > 0
&& Objects.equals(r.getOrgScopeId(), actor.departmentId()) && "0".equals(r.getStatus()))
.limit(20).map(r -> new SubjectCandidate("ROLE:" + r.getRoleId(), type, r.getRoleName())).toList();
} catch (RuntimeException e) {
throw AccessControlDomainException.validation("主体候选加载失败,请重试");
}
}
void require(SubjectType type, String reference, AccessControlActorProvider.Actor actor) {
if (type == null || reference == null || !reference.matches(type.name() + ":[1-9][0-9]{0,18}")) {
throw AccessControlDomainException.validation("主体类型与所选主体不匹配");
}
try {
long id = Long.parseLong(reference.substring(reference.indexOf(':') + 1));
boolean valid = switch (type) {
case USER -> users.selectListByIds(List.of(id)).stream().anyMatch(u ->
Objects.equals(u.getUserId(), id) && Objects.equals(u.getDeptId(), actor.departmentId())
&& "0".equals(u.getStatus()));
case ROLE -> {
var role = roles.selectActiveRoleByIdAndDept(id, actor.departmentId());
yield role != null && Objects.equals(role.getRoleId(), id)
&& Objects.equals(role.getOrgScopeId(), actor.departmentId()) && "0".equals(role.getStatus());
}
case DEPARTMENT -> id == actor.departmentId() && departments.selectDeptsByList().stream()
.anyMatch(d -> Objects.equals(d.getDeptId(), id));
};
if (!valid) throw AccessControlDomainException.validation("主体已失效或不在可用范围内");
} catch (RuntimeException e) {
throw AccessControlDomainException.validation("主体校验失败,请重新选择");
}
}
record SubjectCandidate(String subjectRef, SubjectType subjectType, String label) { }
}
@@ -0,0 +1,79 @@
package cn.aixunkeji.datagov.governance.aiassistant;
import cn.aixunkeji.datagov.governance.api.aiassistant.GovernanceAiSuggestionApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.ArrayList;
/** Server-side evidence owner. It never trusts evidence references from a client. */
@Component @RequiredArgsConstructor
class GovernanceAiEvidenceOwner {
private final JdbcTemplate jdbc;
Resolution resolve(GovernanceAiSuggestionActorProvider.Actor a, SuggestionType type, String targetRef) {
String[] p=targetRef.split(":",2); if(p.length!=2 || !p[1].matches("[0-9]+")) return Resolution.outOfScope();
long id=Long.parseLong(p[1]); String table=switch(type) {
case FAILURE_DIAGNOSIS -> "dq_quality_issue";
case METADATA_ENRICHMENT -> "sec_metadata_snapshot";
case STANDARD_MATCH -> "std_external_standard";
case QUALITY_RULE -> "dq_quality_rule";
case GOVERNANCE_WORKFLOW -> "std_standard_request";
};
String expected=switch(type) {
case FAILURE_DIAGNOSIS -> "quality-issue";
case METADATA_ENRICHMENT -> "metadata";
case STANDARD_MATCH -> "standard";
case QUALITY_RULE -> "quality-rule";
case GOVERNANCE_WORKFLOW -> "workflow";
};
if(!expected.equals(p[0])) return Resolution.outOfScope();
String summary;
try {
summary=switch(type) {
case FAILURE_DIAGNOSIS -> jdbc.query("SELECT issue_status,version,update_time FROM dq_quality_issue WHERE issue_id=? AND organization_id=? AND department_id=? AND del_flag='0' AND issue_status NOT IN ('CLOSED','VERIFIED')",(r,n)->r.getString(1)+"/v"+r.getLong(2)+"/"+r.getTimestamp(3),id,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null);
case METADATA_ENRICHMENT -> jdbc.query("SELECT evidence_status,reliable_flag,version,observed_at FROM sec_metadata_snapshot WHERE snapshot_id=? AND organization_id=? AND department_id=? AND del_flag='0' AND evidence_status='RELIABLE' AND reliable_flag='1' AND observed_at>=TIMESTAMPADD(DAY,-7,NOW())",(r,n)->r.getString(1)+"/v"+r.getLong(3)+"/"+r.getTimestamp(4),id,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null);
case STANDARD_MATCH -> jdbc.query("SELECT standard_status,version,expiry_date,update_time FROM std_external_standard WHERE standard_id=? AND organization_id=? AND department_id=? AND del_flag='0' AND standard_status='ACTIVE' AND (expiry_date IS NULL OR expiry_date>=CURRENT_DATE)",(r,n)->r.getString(1)+"/v"+r.getLong(2)+"/"+r.getDate(3)+"/"+r.getTimestamp(4),id,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null);
case QUALITY_RULE -> jdbc.query("SELECT rule_status,version,update_time FROM dq_quality_rule WHERE rule_id=? AND organization_id=? AND department_id=? AND del_flag='0' AND rule_status='ENABLED'",(r,n)->r.getString(1)+"/v"+r.getLong(2)+"/"+r.getTimestamp(3),id,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null);
case GOVERNANCE_WORKFLOW -> jdbc.query("""
SELECT r.request_status,r.version,r.update_time,s.system_code,s.system_name,
s.standard_type,s.business_domain,s.system_status,s.version
FROM std_standard_request r
JOIN std_standard_system s ON s.system_id=r.response_system_id
AND s.organization_id=r.organization_id AND s.department_id=r.department_id
AND s.del_flag='0'
WHERE r.request_record_id=? AND r.organization_id=? AND r.department_id=?
AND r.del_flag='0' AND r.request_status='COMPLETED'
""",(r,n)->r.getString(1)+"/request-v"+r.getLong(2)+"/"+r.getTimestamp(3)
+";system="+r.getString(4)+"/"+r.getString(5)+"/"+r.getString(6)
+"/"+r.getString(7)+"/"+r.getString(8)+"/v"+r.getLong(9),
id,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null);
};
} catch (org.springframework.dao.DataAccessException ex) { return Resolution.outOfScope(); }
return summary!=null ? Resolution.success(List.of("owner:"+table+":"+id),summary) : Resolution.insufficient();
}
private String idColumn(String table){ return switch(table){case "dq_quality_issue"->"issue_id";case "sec_metadata_snapshot"->"snapshot_id";case "std_external_standard"->"standard_id";case "dq_quality_rule"->"rule_id";default->"request_id";}; }
List<Candidate> candidates(GovernanceAiSuggestionActorProvider.Actor a, SuggestionType type, String keyword, int limit) {
String like = "%" + keyword + "%";
if (type == SuggestionType.QUALITY_RULE) return jdbc.query("SELECT rule_name,rule_id,object_fqn,version FROM dq_quality_rule WHERE organization_id=? AND department_id=? AND del_flag='0' AND rule_status='ENABLED' AND (rule_name LIKE ? OR object_fqn LIKE ?) ORDER BY rule_name,rule_id LIMIT ?", (r,n)->new Candidate(r.getString(1)+" · "+r.getString(3), "quality-rule:"+r.getLong(2), "QUALITY_RULE", String.valueOf(r.getLong(4)), null), a.organizationId(),a.departmentId(),like,like,limit);
if (type == SuggestionType.GOVERNANCE_WORKFLOW) return jdbc.query("""
SELECT s.system_code,s.system_name,r.request_record_id,r.version,r.update_time
FROM std_standard_request r
JOIN std_standard_system s ON s.system_id=r.response_system_id
AND s.organization_id=r.organization_id AND s.department_id=r.department_id
AND s.del_flag='0'
WHERE r.organization_id=? AND r.department_id=? AND r.del_flag='0'
AND r.request_status='COMPLETED'
AND (s.system_code LIKE ? OR s.system_name LIKE ?)
ORDER BY r.update_time DESC,r.request_record_id DESC LIMIT ?
""", (r,n)->new Candidate(r.getString(1)+" · "+r.getString(2),
"workflow:"+r.getLong(3), "GOVERNANCE_WORKFLOW", String.valueOf(r.getLong(4)),
r.getTimestamp(5).toLocalDateTime()), a.organizationId(),a.departmentId(),like,like,limit);
return jdbc.query("SELECT source_ref,snapshot_id,source_type,version,observed_at FROM sec_metadata_snapshot WHERE organization_id=? AND department_id=? AND del_flag='0' AND evidence_status='RELIABLE' AND reliable_flag='1' AND observed_at>=TIMESTAMPADD(DAY,-7,NOW()) AND source_ref IS NOT NULL AND source_ref<>'' AND source_ref LIKE ? ORDER BY observed_at DESC,snapshot_id DESC LIMIT ?", (r,n)->new Candidate(r.getString(1)+" · "+r.getString(3), "metadata:"+r.getLong(2), "METADATA_ENRICHMENT", String.valueOf(r.getLong(4)), r.getTimestamp(5).toLocalDateTime()), a.organizationId(),a.departmentId(),like,limit);
}
record Resolution(List<String> refs,String summary,String failure){
static Resolution success(List<String> refs,String summary){return new Resolution(refs,summary,null);}
static Resolution outOfScope(){return new Resolution(List.of(),null,"OUT_OF_SCOPE");}
static Resolution insufficient(){return new Resolution(List.of(),null,"EVIDENCE_INSUFFICIENT");}
}
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.governance.aiassistant;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class GovernanceAiSuggestionActorProvider {
Actor current() {
Long user = LoginHelper.getUserId(), dept = LoginHelper.getDeptId();
if (user == null || dept == null || user <= 0 || dept <= 0) throw GovernanceAiSuggestionDomainException.forbidden();
return new Actor(user, dept, dept);
}
record Actor(long actorId, long organizationId, long departmentId) { }
}
@@ -0,0 +1,25 @@
package cn.aixunkeji.datagov.governance.aiassistant;
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.governance.api.aiassistant.GovernanceAiSuggestionApi.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;
@RestController @RequiredArgsConstructor @RequestMapping("/api/governance/v1/ai-suggestions")
public class GovernanceAiSuggestionController {
private final GovernanceAiSuggestionService service;
@SaCheckPermission("aixun:ai:assistant:view") @GetMapping public R<List<SuggestionView>> page(){return R.ok(service.page());}
@SaCheckPermission("aixun:ai:assistant:generate") @GetMapping("/candidates") public R<List<Candidate>> candidates(@RequestParam String type, @RequestParam(required=false, defaultValue="") String keyword, @RequestParam(required=false, defaultValue="20") int limit){
try { return R.ok(service.candidates(SuggestionType.valueOf(type), keyword, limit)); }
catch (IllegalArgumentException e) { throw GovernanceAiSuggestionDomainException.validation("候选类型或上限无效"); }
}
@SaCheckPermission("aixun:ai:assistant:view") @GetMapping("/{id}") public R<SuggestionView> detail(@PathVariable long id){return R.ok(service.detail(id));}
@Log(title="AI治理建议生成",businessType=BusinessType.INSERT,isSaveRequestData=false,isSaveResponseData=false) @SaCheckPermission("aixun:ai:assistant:generate") @PostMapping public R<SuggestionView> generate(@RequestBody GenerateCommand c){return R.ok(service.generate(c));}
@Log(title="AI治理建议采纳",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false) @SaCheckPermission("aixun:ai:assistant:adopt") @PostMapping("/{id}/adopt") public R<SuggestionView> adopt(@PathVariable long id,@RequestBody AdoptCommand c){return R.ok(service.adopt(id,c));}
@Log(title="AI治理建议忽略",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false) @SaCheckPermission("aixun:ai:assistant:adopt") @PostMapping("/{id}/ignore") public R<SuggestionView> ignore(@PathVariable long id,@RequestBody AdoptCommand c){return R.ok(service.ignore(id,c));}
}
@@ -0,0 +1,16 @@
package cn.aixunkeji.datagov.governance.aiassistant;
import org.springframework.http.HttpStatus;
final class GovernanceAiSuggestionDomainException extends RuntimeException {
static final int VALIDATION_CODE=134001, FORBIDDEN_CODE=134003, NOT_FOUND_CODE=134004, CONFLICT_CODE=134009;
private final HttpStatus status;
private final int code;
private GovernanceAiSuggestionDomainException(HttpStatus status,int code, String message) { super(message); this.status = status; this.code=code; }
static GovernanceAiSuggestionDomainException validation(String m) { return new GovernanceAiSuggestionDomainException(HttpStatus.BAD_REQUEST,VALIDATION_CODE, m); }
static GovernanceAiSuggestionDomainException forbidden() { return new GovernanceAiSuggestionDomainException(HttpStatus.FORBIDDEN,FORBIDDEN_CODE, "无权访问AI治理建议"); }
static GovernanceAiSuggestionDomainException notFound() { return new GovernanceAiSuggestionDomainException(HttpStatus.NOT_FOUND,NOT_FOUND_CODE, "AI治理建议不存在"); }
static GovernanceAiSuggestionDomainException conflict(String m) { return new GovernanceAiSuggestionDomainException(HttpStatus.CONFLICT,CONFLICT_CODE, m); }
HttpStatus status() { return status; }
int code() { return code; }
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.governance.aiassistant;
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 = GovernanceAiSuggestionController.class)
class GovernanceAiSuggestionExceptionHandler {
@ExceptionHandler(GovernanceAiSuggestionDomainException.class)
ResponseEntity<R<Void>> handle(GovernanceAiSuggestionDomainException e) {
return ResponseEntity.status(e.status()).body(R.fail(e.code(), e.getMessage()));
}
}
@@ -0,0 +1,26 @@
package cn.aixunkeji.datagov.governance.aiassistant;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.governance.api.aiassistant.GovernanceAiSuggestionApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.time.LocalDateTime;
import java.util.*;
@Repository @RequiredArgsConstructor
class GovernanceAiSuggestionJdbcRepository {
private final JdbcTemplate jdbc;
private final String select = "SELECT suggestion_id,request_id,suggestion_type,target_ref,proposal,rationale,evidence_refs,confidence,impact,\"MODEL\",provider_version,state,failure_code,organization_id,department_id,version,create_time,update_time FROM wb_ai_governance_suggestion ";
SuggestionView find( GovernanceAiSuggestionActorProvider.Actor a, String requestId) { return jdbc.query(select+"WHERE request_id=? AND organization_id=? AND department_id=? AND del_flag='0'", this::map, requestId,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null); }
String requestHash(GovernanceAiSuggestionActorProvider.Actor a, String requestId) { return jdbc.query("SELECT request_sha256 FROM wb_ai_governance_suggestion WHERE request_id=? AND organization_id=? AND department_id=? AND del_flag='0'",(r,n)->r.getString(1),requestId,a.organizationId(),a.departmentId()).stream().findFirst().orElse(null); }
SuggestionView get(GovernanceAiSuggestionActorProvider.Actor a,long id) { return jdbc.query(select+"WHERE suggestion_id=? AND organization_id=? AND department_id=? AND del_flag='0'",this::map,id,a.organizationId(),a.departmentId()).stream().findFirst().orElseThrow(GovernanceAiSuggestionDomainException::notFound); }
List<SuggestionView> page(GovernanceAiSuggestionActorProvider.Actor a) { return jdbc.query(select+"WHERE organization_id=? AND department_id=? AND del_flag='0' ORDER BY update_time DESC,suggestion_id DESC",this::map,a.organizationId(),a.departmentId()); }
long insert(GovernanceAiSuggestionActorProvider.Actor a, GenerateCommand c, String hash, List<String> evidenceRefs, String proposal,String rationale,double confidence,String impact,String model,String pv,String failure) {
long id=IdGeneratorUtil.nextLongId(); jdbc.update("INSERT INTO wb_ai_governance_suggestion(suggestion_id,request_id,request_sha256,suggestion_type,target_ref,proposal,rationale,evidence_refs,confidence,impact,\"MODEL\",provider_version,state,failure_code,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,version,del_flag) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),0,'0')",id,c.requestId(),hash,c.type().name(),c.targetRef(),proposal,rationale,String.join("\n",evidenceRefs),confidence,impact,model,pv,"DRAFT",failure,a.organizationId(),a.departmentId(),a.departmentId(),a.actorId(),a.actorId()); return id;
}
SuggestionView state(GovernanceAiSuggestionActorProvider.Actor a,long id,State target,long version) { int n=jdbc.update("UPDATE wb_ai_governance_suggestion SET state=?,version=version+1,update_by=?,update_time=NOW() WHERE suggestion_id=? AND organization_id=? AND department_id=? AND version=? AND state='DRAFT' AND del_flag='0'",target.name(),a.actorId(),id,a.organizationId(),a.departmentId(),version); if(n!=1) throw GovernanceAiSuggestionDomainException.conflict("建议已处理或版本已变化"); return get(a,id); }
private SuggestionView map(ResultSet r,int n)throws java.sql.SQLException { return new SuggestionView(r.getLong("suggestion_id"),r.getString("request_id"),SuggestionType.valueOf(r.getString("suggestion_type")),r.getString("target_ref"),r.getString("proposal"),r.getString("rationale"),split(r.getString("evidence_refs")),r.getDouble("confidence"),r.getString("impact"),r.getString("model"),r.getString("provider_version"),State.valueOf(r.getString("state")),r.getString("failure_code"),r.getLong("organization_id"),r.getLong("department_id"),r.getLong("version"),r.getObject("create_time",LocalDateTime.class),r.getObject("update_time",LocalDateTime.class)); }
private List<String> split(String s){ return s==null||s.isBlank()?List.of():List.of(s.split("\\n")); }
}
@@ -0,0 +1,26 @@
package cn.aixunkeji.datagov.governance.aiassistant;
import cn.aixunkeji.datagov.governance.api.aiassistant.GovernanceAiSuggestionApi.*;
import org.springframework.stereotype.Component;
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.regex.Pattern;
@Component
class GovernanceAiSuggestionPolicy {
private static final Pattern ID = Pattern.compile("[A-Za-z0-9._:-]{8,128}");
private static final Pattern REF = Pattern.compile("[A-Za-z0-9._:/-]{1,512}");
GenerateCommand normalize(GenerateCommand c) {
if (c == null || c.type() == null) throw GovernanceAiSuggestionDomainException.validation("建议请求不完整");
if (c.requestId() == null || !ID.matcher(c.requestId()).matches()) throw GovernanceAiSuggestionDomainException.validation("requestId格式无效");
if (c.targetRef() == null || !REF.matcher(c.targetRef()).matches() || c.targetRef().matches("(?i).*(jdbc|password|secret|token|authorization).*")) throw GovernanceAiSuggestionDomainException.validation("targetRef格式无效");
if (c.context() == null || c.context().isBlank() || c.context().length() > 4000) throw GovernanceAiSuggestionDomainException.validation("上下文不能为空且不得超过4000字");
return new GenerateCommand(c.requestId(), c.type(), c.targetRef(), c.context());
}
AdoptCommand version(AdoptCommand c) { if (c == null || c.version() == null || c.version() < 0) throw GovernanceAiSuggestionDomainException.validation("版本不能为空"); return c; }
String requestHash(GenerateCommand c) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest((c.type().name()+"|"+c.targetRef()+"|"+c.context()).getBytes(StandardCharsets.UTF_8))); }
catch (Exception e) { throw new IllegalStateException("请求摘要失败",e); }
}
}
@@ -0,0 +1,47 @@
package cn.aixunkeji.datagov.governance.aiassistant;
import cn.aixunkeji.datagov.governance.api.aiassistant.GovernanceAiSuggestionApi.*;
import cn.aixunkeji.datagov.integration.api.aiassistant.AiProviderApi;
import cn.aixunkeji.datagov.integration.api.aiassistant.AiProviderApi.*;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import java.util.List;
@Service @RequiredArgsConstructor
class GovernanceAiSuggestionService {
private static final int DRAFT_MAX_TOKENS = 1536;
private final GovernanceAiSuggestionJdbcRepository repository;
private final GovernanceAiSuggestionPolicy policy;
private final GovernanceAiSuggestionActorProvider actors;
private final GovernanceAiEvidenceOwner evidenceOwner;
@DubboReference(check=false, retries=0, timeout=12000) private AiProviderApi provider;
SuggestionView generate(GenerateCommand raw) {
var a=actors.current(); var c=policy.normalize(raw); String hash=policy.requestHash(c); var old=repository.find(a,c.requestId()); if(old!=null) { if(!hash.equals(repository.requestHash(a,c.requestId()))) throw GovernanceAiSuggestionDomainException.conflict("相同requestId的请求载荷不一致"); return old; }
var evidence=evidenceOwner.resolve(a,c.type(),c.targetRef());
if(evidence.failure()!=null) return view(a,c,hash,evidence.refs(),"", "对象不在当前 Actor 可读范围内,未调用Provider",0,"NONE","none","none",evidence.failure());
if(evidence.refs().isEmpty()) return view(a,c,hash,evidence.refs(),"", "不能生成建议:缺少可追溯证据",0,"NONE","none","none","EVIDENCE_INSUFFICIENT");
String authoritativeEvidence = "服务端证据摘要=" + evidence.summary() + ";稳定引用=" + String.join(",", evidence.refs());
CompletionRequest request=new CompletionRequest(c.requestId(), c.type().name(), "只输出结构化建议草稿;不得执行、修改或发布对象", c.context(), authoritativeEvidence, DRAFT_MAX_TOKENS);
SuggestionResponse response;
try { response=provider.complete(a.actorId(),request); } catch(Exception e) { return view(a,c,hash,evidence.refs(),"","Provider不可用,建议未生成",0,"NONE","none","none","PROVIDER_ERROR"); }
if(!"DRAFT".equals(response.status())) return view(a,c,hash,evidence.refs(),"",response.summary()==null?"Provider未生成草稿":response.summary(),0,"NONE",response.model(),response.providerVersion(),response.code());
return view(a,c,hash,evidence.refs(),response.summary(),"服务端证据摘要="+evidence.summary()+";仅由受控Provider返回结构化草稿,未执行任何治理命令",0.5,"REVIEW_REQUIRED",response.model(),response.providerVersion(),null);
}
SuggestionView detail(long id){return repository.get(actors.current(),id);} List<SuggestionView> page(){return repository.page(actors.current());}
List<Candidate> candidates(SuggestionType type, String keyword, int limit) {
if (type != SuggestionType.QUALITY_RULE && type != SuggestionType.METADATA_ENRICHMENT
&& type != SuggestionType.GOVERNANCE_WORKFLOW) {
throw GovernanceAiSuggestionDomainException.validation("仅支持质量规则、可靠元数据和标准治理流程候选");
}
if (keyword == null || keyword.length() > 100 || limit < 1 || limit > 50) throw GovernanceAiSuggestionDomainException.validation("候选关键字或上限无效");
return evidenceOwner.candidates(actors.current(), type, keyword, limit);
}
SuggestionView adopt(long id,AdoptCommand c){return repository.state(actors.current(),id,State.ADOPTED,policy.version(c).version());}
SuggestionView ignore(long id,AdoptCommand c){return repository.state(actors.current(),id,State.IGNORED,policy.version(c).version());}
private SuggestionView view(GovernanceAiSuggestionActorProvider.Actor a,GenerateCommand c,String hash,List<String> refs,String p,String r,double confidence,String impact,String model,String pv,String failure){
long id; try { id=repository.insert(a,c,hash,refs,p,r,confidence,impact,model,pv,failure); } catch(org.springframework.dao.DuplicateKeyException e) { throw GovernanceAiSuggestionDomainException.conflict("请求并发冲突,请读取已有结果"); } return repository.get(a,id);
}
}
@@ -0,0 +1,76 @@
package cn.aixunkeji.datagov.governance.aischeduleinput;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.datagov.governance.nativemetadata.NativeMetadataAccess;
import cn.aixunkeji.datagov.governance.nativemetadata.NativeMetadataMode;
import cn.aixunkeji.datagov.integration.api.aiassistant.*;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.*;
import static cn.aixunkeji.datagov.integration.api.aiassistant.AssistantScheduleInputGuard.*;
@DubboService(version=AssistantScheduleInputDirectory.VERSION,group="governance",timeout=8000,retries=0)
public class GovernanceScheduleInputDirectory implements AssistantScheduleInputDirectory {
private final JdbcTemplate jdbc;
private final NativeMetadataMode mode;
private final NativeMetadataAccess sources;
@DubboReference(check=false,timeout=5000,retries=0) private RemoteUserService users;
@DubboReference(version=AssistantScheduleContext.VERSION,check=false,timeout=5000,retries=0) private AssistantScheduleContext schedules;
public GovernanceScheduleInputDirectory(JdbcTemplate jdbc,NativeMetadataMode mode,NativeMetadataAccess sources) {this.jdbc=jdbc;this.mode=mode;this.sources=sources;}
private void type(String kind) {if(!Set.of("METADATA_TABLE","QUALITY_RULE").contains(kind==null?"":kind))throw denied();}
private void ref(Input r) {kind(r,"METADATA_TABLE","QUALITY_RULE"); if(r.kind().equals("QUALITY_RULE"))numeric(r,"QUALITY_RULE");else if(!r.id().matches("[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}"))throw denied();}
private Principal currentActor(String kind) {type(kind);var a=principal(LoginHelper.getUserId(),LoginHelper.getDeptId());authority(a,kind,null);return a;}
private void authority(Principal a,String kind,String schedule) {
String purpose="SCHEDULE_INPUT_"+kind;
var d=schedule==null?users.resolveAssetActor(a.user(),a.department(),purpose):users.resolveAssistantInputActor(a.user(),a.department(),schedule,kind);
if(d==null||!d.allowed()||d.userId()!=a.user()||d.deptId()!=a.department()||!purpose.equals(d.purpose())||!fresh(d.checkedAt()))throw denied();
}
@Override public List<Candidate> candidates(String kind,String search) {
var a=currentActor(kind);String like="%"+keyword(search)+"%";List<Candidate> result;
if(kind.equals("QUALITY_RULE")) result=jdbc.query("SELECT rule_id,rule_name,version FROM dq_quality_rule WHERE organization_id=? AND department_id=? AND del_flag='0' AND rule_name LIKE ? ESCAPE '=' ORDER BY rule_id LIMIT 20",
(r,n)->new Candidate(kind,r.getString(1),r.getString(2),r.getLong(3),"/quality-rule"),a.department(),a.department(),like);
else {
if(!mode.nativeActive())throw denied();
record Row(Candidate candidate,long source) { }
var rows=jdbc.query("SELECT entity_id,entity_name,row_version,source_id FROM md_native_entity WHERE org_id=? AND entity_kind='TABLE' AND source_id IS NOT NULL AND deleted_flag=FALSE AND del_flag='0' AND entity_name LIKE ? ESCAPE '=' ORDER BY entity_id LIMIT 20",
(r,n)->new Row(new Candidate(kind,r.getString(1),r.getString(2),r.getLong(3),"/metadata-catalog"),r.getLong(4)),a.department(),like);
var permitted=new HashMap<Long,Boolean>();var found=new ArrayList<Candidate>();
for(var row:rows) {
boolean allowed=permitted.computeIfAbsent(row.source(),id->{try{sources.source(new NativeMetadataAccess.Actor(a.user(),a.department()),id,null);return true;}catch(RuntimeException e){return false;}});
if(allowed)found.add(row.candidate());
}
result=List.copyOf(found);
}
authority(a,kind,null);return result;
}
@Override public Snapshot current(Input ref,Instant end,String timezone) {ref(ref);var a=currentActor(ref.kind());var result=read(a,ref,end,timezone);authority(a,ref.kind(),null);return result;}
@Override public Snapshot background(String schedule,String run,Input ref) {
ref(ref);var proof=schedules.objectScope(schedule,run,ref.kind(),ref.id());var a=scope(proof,schedule,run,ref);authority(a,ref.kind(),schedule);
var result=read(a,ref,proof.scheduledAt(),proof.timezone());authority(a,ref.kind(),schedule);
if(!a.equals(scope(schedules.objectScope(schedule,run,ref.kind(),ref.id()),schedule,run,ref)))throw denied();return result;
}
private Snapshot read(Principal a,Input ref,Instant end,String timezone) {
if(ref.kind().equals("METADATA_TABLE"))return table(a,ref);
var w=window(end,timezone);
var records=jdbc.query("SELECT rule_name,version,rule_status,severity_code,sql_validation_status FROM dq_quality_rule WHERE rule_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
(r,n)->new Snapshot(ref,r.getLong(2),r.getString(1),"/quality-rule",Map.of("规则状态",r.getString(3),"严重程度",r.getString(4),"自定义SQL验证状态",r.getString(5)==null?"不适用":r.getString(5)),Instant.now()),Long.parseLong(ref.id()),a.department(),a.department());
if(records.size()!=1)throw denied();var record=records.getFirst();var facts=new LinkedHashMap<>(record.facts());
facts.put("统计范围",w.from()+" 至 "+w.until()+"(截止执行日期前的7天)");
var counts=jdbc.query("SELECT validation_status,COUNT(*) FROM dq_quality_rule_validation WHERE rule_id=? AND organization_id=? AND department_id=? AND del_flag='0' AND create_time>=? AND create_time<? GROUP BY validation_status",
(r,n)->Map.entry(r.getString(1),r.getLong(2)),Long.parseLong(ref.id()),a.department(),a.department(),Timestamp.from(w.from()),Timestamp.from(w.until()));
long count=0;for(var item:counts){facts.put("规则验证_"+item.getKey(),item.getValue().toString());count+=item.getValue();}
facts.put("规则验证总数",Long.toString(count));facts.put("记录范围说明","仅规则验证记录,不代表所有质量任务执行情况;未读取错误原文或业务样本");
facts.put("根因和下游影响","未取得完整证据,需人工继续核查");
return new Snapshot(ref,record.version(),record.name(),record.path(),Map.copyOf(facts),Instant.now());
}
private Snapshot table(Principal a,Input ref) {
if(!mode.nativeActive())throw denied();
record Row(Snapshot value,long source) { }
var rows=jdbc.query("SELECT entity_name,row_version,source_id,observed_at,JSON_LENGTH(JSON_EXTRACT(payload,'$.columns')) FROM md_native_entity WHERE entity_id=? AND org_id=? AND entity_kind='TABLE' AND source_id IS NOT NULL AND deleted_flag=FALSE AND del_flag='0'",
(r,n)->{var facts=new LinkedHashMap<String,String>();facts.put("列数量",r.getObject(5)==null?"未取得":r.getString(5));facts.put("最近元数据观测",r.getTimestamp(4)==null?"未取得":r.getTimestamp(4).toString());facts.put("数据容量、活跃度和访问频次","未取得;不能据此判定低活或僵尸表");facts.put("血缘刷新","未执行;本输入只读取已登记元数据");return new Row(new Snapshot(ref,r.getLong(2),r.getString(1),"/metadata-catalog",Map.copyOf(facts),Instant.now()),r.getLong(3));},ref.id(),a.department());
if(rows.size()!=1)throw denied();var row=rows.getFirst();sources.source(new NativeMetadataAccess.Actor(a.user(),a.department()),row.source(),null);return row.value();
}
}
@@ -0,0 +1,17 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class AnomalyDetectionActorProvider {
Actor current() {
Long actorId = LoginHelper.getUserId();
Long departmentId = LoginHelper.getDeptId();
if (actorId == null || departmentId == null || actorId <= 0 || departmentId <= 0) {
throw AnomalyDetectionDomainException.forbidden();
}
return new Actor(actorId, departmentId, departmentId);
}
record Actor(long actorId, long organizationId, long departmentId) { }
}
@@ -0,0 +1,82 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
final class AnomalyDetectionApi {
private AnomalyDetectionApi() { }
enum DetectionType { SCHEMA, VOLUME, DISTRIBUTION, FRESHNESS }
enum ThresholdStrategy { FIXED, BASELINE }
enum Status { ENABLED, DISABLED }
enum Severity { INFO, LOW, MEDIUM, HIGH, CRITICAL }
enum SourceType { OPENMETADATA, DORIS, HIVE, DOLPHINSCHEDULER, DATAGOV }
enum Verdict { NORMAL, ANOMALY, UNKNOWN }
record ProfileTargetSelection(String snapshotId,String fingerprint) { }
record CreateCommand(String detectionCode, String detectionName, DetectionType detectionType,
String targetLogicalId, String targetFqn, String expectedSchemaFingerprint, Severity severity,
ThresholdStrategy thresholdStrategy, BigDecimal fixedLower, BigDecimal fixedUpper,
Integer minimumSamples, Integer historyLimit, BigDecimal deviationMultiplier,
List<SourceType> allowedSources, @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) ProfileTargetSelection profileTarget) {
CreateCommand(String code,String name,DetectionType type,String target,String fqn,String schema,Severity severity,
ThresholdStrategy strategy,BigDecimal lower,BigDecimal upper,Integer minimum,Integer history,BigDecimal multiplier,List<SourceType> sources){
this(code,name,type,target,fqn,schema,severity,strategy,lower,upper,minimum,history,multiplier,sources,null);
}
}
record UpdateCommand(String detectionName, String targetLogicalId, String targetFqn,
String expectedSchemaFingerprint, Severity severity,
ThresholdStrategy thresholdStrategy, BigDecimal fixedLower, BigDecimal fixedUpper,
Integer minimumSamples, Integer historyLimit, BigDecimal deviationMultiplier,
List<SourceType> allowedSources, Long version, @com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL) ProfileTargetSelection profileTarget) {
UpdateCommand(String name,String target,String fqn,String schema,Severity severity,ThresholdStrategy strategy,BigDecimal lower,
BigDecimal upper,Integer minimum,Integer history,BigDecimal multiplier,List<SourceType> sources,Long version){
this(name,target,fqn,schema,severity,strategy,lower,upper,minimum,history,multiplier,sources,version,null);
}
}
record StatusCommand(Status targetStatus, String reason, Long version) { }
/** A closed, type-aware observation whitelist. No arbitrary body, SQL, URL or credential field exists. */
record ObservationCommand(SourceType sourceType, String externalRef, LocalDateTime observedAt,
String payloadSha, boolean reliable, String unreliableReason,
String schemaFingerprint, Long rowCount, Boolean emptyBatch, Boolean interrupted,
BigDecimal mean, BigDecimal standardDeviation, BigDecimal minimum,
BigDecimal maximum, BigDecimal nullRatio, LocalDateTime dataUpdatedAt,
LocalDateTime arrivedAt, Long processingDelaySeconds, Long version) { }
record EvaluateCommand(long observationId, Long version) { }
record BaselineCommand(Integer sampleCount, Long version) { }
record DetectionView(long detectionId, String detectionCode, String detectionName,
DetectionType detectionType, String targetLogicalId, String targetFqn,
String expectedSchemaFingerprint,
Severity severity, ThresholdStrategy thresholdStrategy, BigDecimal fixedLower,
BigDecimal fixedUpper, int minimumSamples, int historyLimit,
BigDecimal deviationMultiplier, List<SourceType> allowedSources, Status status,
long organizationId, long departmentId, long version,
LocalDateTime createTime, LocalDateTime updateTime) { }
record ObservationView(long observationId, long detectionId, SourceType sourceType, String externalRef,
LocalDateTime observedAt, String payloadSha, boolean reliable,
String unreliableReason, String schemaFingerprint, Long rowCount,
Boolean emptyBatch, Boolean interrupted, BigDecimal mean,
BigDecimal standardDeviation, BigDecimal minimum, BigDecimal maximum,
BigDecimal nullRatio, LocalDateTime dataUpdatedAt, LocalDateTime arrivedAt,
Long processingDelaySeconds, LocalDateTime createTime) { }
record BaselineView(long baselineId, long detectionId, String algorithm, String algorithmVersion,
int sampleCount, BigDecimal lowerBound, BigDecimal upperBound,
String fallbackReason, LocalDateTime createTime) { }
record ResultView(long resultId, long detectionId, long observationId, long configVersion,
String observationSha, Verdict verdict, String reasonCode, String reasonSummary,
String inputSummarySha, String algorithm, String algorithmVersion, Integer sampleCount,
BigDecimal lowerBound, BigDecimal upperBound, String fallbackReason,
LocalDateTime evaluatedAt) { }
record WriteView<T>(String requestId, T result) { }
}
@@ -0,0 +1,114 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
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.governance.anomalydetection.AnomalyDetectionApi.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/governance/v1/anomaly-detections")
public class AnomalyDetectionController {
private final cn.aixunkeji.datagov.governance.qualityissue.QualityIssueCandidates identityCandidates;
@SaCheckPermission(value={"aixun:governance:anomaly-detection:create","aixun:governance:anomaly-detection:update"},mode=cn.dev33.satoken.annotation.SaMode.OR)
@GetMapping("/candidates/targets")
public R<java.util.List<cn.aixunkeji.datagov.governance.qualityissue.QualityIssueCandidates.Target>> targets() {
var a=new AnomalyDetectionActorProvider().current(); return R.ok(identityCandidates.targets(a.organizationId(),a.departmentId()));
}
private final AnomalyDetectionService service;
@SaCheckPermission("aixun:governance:anomaly-detection:view")
@GetMapping
public R<PageResult<DetectionView>> page(@RequestParam(required = false) String keyword,
@RequestParam(required = false) DetectionType type,
@RequestParam(required = false) Status status,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.page(keyword, type, status, pageNum, pageSize));
}
@SaCheckPermission("aixun:governance:anomaly-detection:view")
@GetMapping("/{detectionId}")
public R<DetectionView> detail(@PathVariable long detectionId) { return R.ok(service.detail(detectionId)); }
@Log(title = "异常检测创建", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:anomaly-detection:create")
@PostMapping
public R<WriteView<DetectionView>> create(@RequestHeader("Idempotency-Key") String key,
@RequestBody CreateCommand command) {
return R.ok(service.create(key, command));
}
@Log(title = "异常检测更新", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:anomaly-detection:update")
@PutMapping("/{detectionId}")
public R<WriteView<DetectionView>> update(@PathVariable long detectionId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody UpdateCommand command) {
return R.ok(service.update(detectionId, key, command));
}
@Log(title = "异常检测状态变更", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:anomaly-detection:status")
@PostMapping("/{detectionId}/status")
public R<WriteView<DetectionView>> status(@PathVariable long detectionId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody StatusCommand command) {
return R.ok(service.status(detectionId, key, command));
}
@SaCheckPermission("aixun:governance:anomaly-detection:view")
@GetMapping("/{detectionId}/observations")
public R<PageResult<ObservationView>> observations(@PathVariable long detectionId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.observations(detectionId, pageNum, pageSize));
}
@Log(title = "异常检测观测登记", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:anomaly-detection:evaluate")
@PostMapping("/{detectionId}/observations")
public R<WriteView<ObservationView>> observe(@PathVariable long detectionId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody ObservationCommand command) {
return R.ok(service.observe(detectionId, key, command));
}
@Log(title = "异常检测评估", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:anomaly-detection:evaluate")
@PostMapping("/{detectionId}/evaluate")
public R<WriteView<ResultView>> evaluate(@PathVariable long detectionId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody EvaluateCommand command) {
return R.ok(service.evaluate(detectionId, key, command));
}
@SaCheckPermission("aixun:governance:anomaly-detection:view")
@GetMapping("/{detectionId}/results")
public R<PageResult<ResultView>> results(@PathVariable long detectionId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.results(detectionId, pageNum, pageSize));
}
@Log(title = "异常检测基线生成", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:anomaly-detection:baseline")
@PostMapping("/{detectionId}/baselines")
public R<WriteView<BaselineView>> baseline(@PathVariable long detectionId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody BaselineCommand command) {
return R.ok(service.baseline(detectionId, key, command));
}
@SaCheckPermission("aixun:governance:anomaly-detection:view")
@GetMapping("/{detectionId}/baselines")
public R<PageResult<BaselineView>> baselines(@PathVariable long detectionId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.baselines(detectionId, pageNum, pageSize));
}
}
@@ -0,0 +1,32 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import org.springframework.http.HttpStatus;
final class AnomalyDetectionDomainException extends RuntimeException {
static final int VALIDATION_CODE = 134001;
static final int FORBIDDEN_CODE = 134003;
static final int NOT_FOUND_CODE = 134004;
static final int CONFLICT_CODE = 134009;
private final int code;
private final HttpStatus status;
private AnomalyDetectionDomainException(int code, HttpStatus status, String message) {
super(message); this.code = code; this.status = status;
}
static AnomalyDetectionDomainException validation(String message) {
return new AnomalyDetectionDomainException(VALIDATION_CODE, HttpStatus.BAD_REQUEST, message);
}
static AnomalyDetectionDomainException forbidden() {
return new AnomalyDetectionDomainException(FORBIDDEN_CODE, HttpStatus.FORBIDDEN, "无权访问异常检测资源");
}
static AnomalyDetectionDomainException notFound() {
return new AnomalyDetectionDomainException(NOT_FOUND_CODE, HttpStatus.NOT_FOUND, "异常检测资源不存在");
}
static AnomalyDetectionDomainException conflict(String message) {
return new AnomalyDetectionDomainException(CONFLICT_CODE, HttpStatus.CONFLICT, message);
}
int code() { return code; }
HttpStatus status() { return status; }
}
@@ -0,0 +1,16 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
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 = AnomalyDetectionController.class)
class AnomalyDetectionExceptionHandler {
@ExceptionHandler(cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner.SourceException.class)
ResponseEntity<R<Void>> source(cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner.SourceException e){return ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
@ExceptionHandler(AnomalyDetectionDomainException.class)
ResponseEntity<R<Void>> handle(AnomalyDetectionDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,327 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionActorProvider.Actor;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionApi.*;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionPolicy.*;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
@Repository
@RequiredArgsConstructor
class AnomalyDetectionJdbcRepository {
private static final String DETECTION_SELECT = """
SELECT detection_id,detection_code,detection_name,detection_type,target_logical_id,target_fqn,
expected_schema_fingerprint,severity_code,threshold_strategy,fixed_lower,fixed_upper,
minimum_samples,history_limit,deviation_multiplier,allowed_sources,detection_status,
organization_id,department_id,version,create_time,update_time
FROM dq_anomaly_detection
""";
private static final String OBSERVATION_SELECT = """
SELECT observation_id,detection_id,source_type,external_ref,observed_at,payload_sha256,reliable_flag,
unreliable_reason,schema_fingerprint,row_count,empty_batch_flag,interrupted_flag,mean_value,
stddev_value,minimum_value,maximum_value,null_ratio,data_updated_at,arrived_at,
processing_delay_seconds,create_time FROM dq_anomaly_observation
""";
private static final String BASELINE_SELECT = """
SELECT baseline_id,detection_id,algorithm_code,algorithm_version,sample_count,lower_bound,upper_bound,
fallback_reason,create_time FROM dq_anomaly_baseline
""";
private static final String RESULT_SELECT = """
SELECT result_id,detection_id,observation_id,config_version,observation_sha256,verdict,reason_code,
reason_summary,input_summary_sha256,algorithm_code,algorithm_version,sample_count,lower_bound,
upper_bound,fallback_reason,evaluated_at FROM dq_anomaly_result
""";
private final JdbcTemplate jdbc;
List<cn.aixunkeji.datagov.governance.api.qualityissue.QualityIssueAssistDirectory.Option> issueEvidenceCandidates(Actor actor,String keyword) {
return jdbc.query("""
SELECT d.detection_id,r.result_id,r.config_version,d.detection_name,d.target_fqn,r.evaluated_at
FROM dq_anomaly_detection d JOIN dq_anomaly_result r ON r.detection_id=d.detection_id
JOIN dq_anomaly_observation o ON o.observation_id=r.observation_id AND o.detection_id=d.detection_id
JOIN dq_anomaly_source_evidence p ON p.result_id=r.result_id AND p.detection_id=d.detection_id
AND p.organization_id=d.organization_id AND p.department_id=d.department_id
WHERE d.organization_id=? AND d.department_id=? AND d.del_flag='0' AND r.del_flag='0' AND o.del_flag='0'
AND r.verdict='ANOMALY' AND r.config_version=d.version AND o.reliable_flag='1' AND r.observation_sha256=o.payload_sha256
AND r.evaluated_at >= ? AND (? IS NULL OR d.detection_name LIKE CONCAT('%',?,'%') OR d.target_fqn LIKE CONCAT('%',?,'%'))
ORDER BY r.evaluated_at DESC,r.result_id DESC LIMIT 50
""",(rs,n)->new cn.aixunkeji.datagov.governance.api.qualityissue.QualityIssueAssistDirectory.Option(rs.getLong(1),rs.getLong(2),rs.getLong(3),rs.getString(4),rs.getString(5),rs.getObject(6,LocalDateTime.class).toString()),
actor.organizationId(),actor.departmentId(),LocalDateTime.now().minusDays(366),keyword,keyword,keyword);
}
DetectionView lockIssueDetection(long id,Actor actor){
return jdbc.query(DETECTION_SELECT+" WHERE detection_id=? AND organization_id=? AND department_id=? AND del_flag='0' FOR UPDATE",this::detectionView,id,actor.organizationId(),actor.departmentId())
.stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound);
}
ResultView lockIssueResult(long id,long detectionId){
return jdbc.query(RESULT_SELECT+" WHERE result_id=? AND detection_id=? AND del_flag='0' FOR UPDATE",this::resultView,id,detectionId)
.stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound);
}
ObservationView lockIssueObservation(long id,long detectionId){
return jdbc.query(OBSERVATION_SELECT+" WHERE observation_id=? AND detection_id=? AND del_flag='0' FOR UPDATE",this::observationView,id,detectionId)
.stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound);
}
DetectionPage page(Actor actor, String keyword, DetectionType type, Status status, int pageNum, int pageSize) {
String typeValue = type == null ? null : type.name(); String statusValue = status == null ? null : status.name();
Long total = jdbc.queryForObject("""
SELECT COUNT(*) FROM dq_anomaly_detection WHERE organization_id=? AND department_id=? AND del_flag='0'
AND (? IS NULL OR detection_code LIKE CONCAT('%', ?, '%') OR detection_name LIKE CONCAT('%', ?, '%'))
AND (? IS NULL OR detection_type=?) AND (? IS NULL OR detection_status=?)
""", Long.class, actor.organizationId(), actor.departmentId(), keyword, keyword, keyword,
typeValue, typeValue, statusValue, statusValue);
List<DetectionView> rows = jdbc.query(DETECTION_SELECT + """
WHERE organization_id=? AND department_id=? AND del_flag='0'
AND (? IS NULL OR detection_code LIKE CONCAT('%', ?, '%') OR detection_name LIKE CONCAT('%', ?, '%'))
AND (? IS NULL OR detection_type=?) AND (? IS NULL OR detection_status=?)
ORDER BY update_time DESC,detection_id DESC LIMIT ? OFFSET ?
""", this::detectionView, actor.organizationId(), actor.departmentId(), keyword, keyword, keyword,
typeValue, typeValue, statusValue, statusValue, pageSize, (pageNum - 1) * pageSize);
return new DetectionPage(rows, total == null ? 0 : total);
}
DetectionView detection(long id, Actor actor) {
return jdbc.query(DETECTION_SELECT + " WHERE detection_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
this::detectionView, id, actor.organizationId(), actor.departmentId()).stream().findFirst()
.orElseThrow(AnomalyDetectionDomainException::notFound);
}
long create(Actor actor, NormalizedDetection value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO dq_anomaly_detection(detection_id,detection_code,detection_name,detection_type,
target_logical_id,target_fqn,expected_schema_fingerprint,severity_code,threshold_strategy,
fixed_lower,fixed_upper,minimum_samples,history_limit,deviation_multiplier,allowed_sources,
detection_status,organization_id,department_id,create_dept,create_by,create_time,update_by,
update_time,del_flag,version)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'DISABLED',?,?,?,?,NOW(),?,NOW(),'0',0)
""", id, value.detectionCode(), value.detectionName(), value.detectionType().name(),
value.targetLogicalId(), value.targetFqn(), value.expectedSchemaFingerprint(), value.severity().name(),
value.thresholdStrategy().name(), value.fixedLower(), value.fixedUpper(), value.minimumSamples(),
value.historyLimit(), value.deviationMultiplier(), value.allowedSourcesCsv(), actor.organizationId(),
actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) { throw AnomalyDetectionDomainException.conflict("同部门检测编码或名称已存在"); }
audit(actor, "DETECTION", id, "CREATE", null, "DISABLED", requestId, "异常检测配置已创建"); return id;
}
void update(Actor actor, long id, NormalizedDetection value, String requestId) {
try {
int changed = jdbc.update("""
UPDATE dq_anomaly_detection SET detection_name=?,target_logical_id=?,target_fqn=?,
expected_schema_fingerprint=?,severity_code=?,threshold_strategy=?,fixed_lower=?,fixed_upper=?,
minimum_samples=?,history_limit=?,deviation_multiplier=?,allowed_sources=?,update_by=?,
update_time=NOW(),version=version+1
WHERE detection_id=? AND organization_id=? AND department_id=? AND version=? AND del_flag='0'
""", value.detectionName(), value.targetLogicalId(), value.targetFqn(), value.expectedSchemaFingerprint(),
value.severity().name(), value.thresholdStrategy().name(), value.fixedLower(), value.fixedUpper(),
value.minimumSamples(), value.historyLimit(), value.deviationMultiplier(), value.allowedSourcesCsv(),
actor.actorId(), id, actor.organizationId(), actor.departmentId(), value.version());
requireChanged(changed);
} catch (DuplicateKeyException exception) { throw AnomalyDetectionDomainException.conflict("同部门检测名称已存在"); }
audit(actor, "DETECTION", id, "UPDATE", null, null, requestId, "异常检测配置已更新");
}
void status(Actor actor, long id, Status current, StatusCommand command, String requestId) {
int changed = jdbc.update("""
UPDATE dq_anomaly_detection SET detection_status=?,update_by=?,update_time=NOW(),version=version+1
WHERE detection_id=? AND organization_id=? AND department_id=? AND detection_status=?
AND version=? AND del_flag='0'
""", command.targetStatus().name(), actor.actorId(), id, actor.organizationId(), actor.departmentId(),
current.name(), command.version());
requireChanged(changed);
audit(actor, "DETECTION", id, "STATUS", current.name(), command.targetStatus().name(), requestId, command.reason());
}
long createObservation(Actor actor, long detectionId, ObservationCommand value, String requestId) {
Long existing = jdbc.query("""
SELECT observation_id FROM dq_anomaly_observation
WHERE detection_id=? AND payload_sha256=? AND del_flag='0'
""", (rs, n) -> rs.getLong(1), detectionId, value.payloadSha()).stream().findFirst().orElse(null);
if (existing != null) return existing;
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO dq_anomaly_observation(observation_id,detection_id,source_type,external_ref,observed_at,
payload_sha256,reliable_flag,unreliable_reason,schema_fingerprint,row_count,empty_batch_flag,
interrupted_flag,mean_value,stddev_value,minimum_value,maximum_value,null_ratio,data_updated_at,
arrived_at,processing_delay_seconds,organization_id,department_id,create_dept,create_by,
create_time,del_flag)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),'0')
""", id, detectionId, value.sourceType().name(), value.externalRef(), value.observedAt(),
value.payloadSha(), value.reliable() ? "1" : "0", value.unreliableReason(), value.schemaFingerprint(),
value.rowCount(), flag(value.emptyBatch()), flag(value.interrupted()), value.mean(), value.standardDeviation(),
value.minimum(), value.maximum(), value.nullRatio(), value.dataUpdatedAt(), value.arrivedAt(),
value.processingDelaySeconds(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
} catch (DuplicateKeyException exception) {
return jdbc.queryForObject("SELECT observation_id FROM dq_anomaly_observation WHERE detection_id=? AND payload_sha256=? AND del_flag='0'",
Long.class, detectionId, value.payloadSha());
}
audit(actor, "OBSERVATION", id, "OBSERVE", null, value.reliable() ? "RELIABLE" : "UNRELIABLE", requestId,
"有界标准化观测已登记"); return id;
}
ObservationView observation(long id) {
return jdbc.query(OBSERVATION_SELECT + " WHERE observation_id=? AND del_flag='0'", this::observationView, id)
.stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound);
}
ObservationView observationForDetection(long id, long detectionId) {
return jdbc.query(OBSERVATION_SELECT + " WHERE observation_id=? AND detection_id=? AND del_flag='0'",
this::observationView, id, detectionId).stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound);
}
ObservationPage observations(long detectionId, int pageNum, int pageSize) {
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM dq_anomaly_observation WHERE detection_id=? AND del_flag='0'", Long.class, detectionId);
List<ObservationView> rows = jdbc.query(OBSERVATION_SELECT + " WHERE detection_id=? AND del_flag='0' ORDER BY observed_at DESC,observation_id DESC LIMIT ? OFFSET ?",
this::observationView, detectionId, pageSize, (pageNum - 1) * pageSize);
return new ObservationPage(rows, total == null ? 0 : total);
}
List<ObservationView> recentReliableObservations(long detectionId, int limit) {
return jdbc.query(OBSERVATION_SELECT + " WHERE detection_id=? AND reliable_flag='1' AND del_flag='0' ORDER BY observed_at DESC,observation_id DESC LIMIT ?",
this::observationView, detectionId, limit);
}
long createBaseline(Actor actor, long detectionId, BaselineCalculation value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
jdbc.update("""
INSERT INTO dq_anomaly_baseline(baseline_id,detection_id,algorithm_code,algorithm_version,sample_count,
lower_bound,upper_bound,fallback_reason,organization_id,department_id,create_dept,create_by,create_time,del_flag)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NOW(),'0')
""", id, detectionId, value.algorithm(), value.version(), value.sampleCount(), value.lower(), value.upper(),
value.fallbackReason(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
audit(actor, "BASELINE", id, "BASELINE", null, value.fallbackReason() == null ? "READY" : "UNKNOWN",
requestId, "可解释历史基线已保存"); return id;
}
BaselineView baseline(long id) { return jdbc.query(BASELINE_SELECT + " WHERE baseline_id=? AND del_flag='0'", this::baselineView, id).stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound); }
BaselineView latestBaseline(long detectionId) { return jdbc.query(BASELINE_SELECT + " WHERE detection_id=? AND del_flag='0' ORDER BY create_time DESC,baseline_id DESC LIMIT 1", this::baselineView, detectionId).stream().findFirst().orElse(null); }
BaselinePage baselines(long detectionId, int pageNum, int pageSize) {
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM dq_anomaly_baseline WHERE detection_id=? AND del_flag='0'", Long.class, detectionId);
List<BaselineView> rows = jdbc.query(BASELINE_SELECT + " WHERE detection_id=? AND del_flag='0' ORDER BY create_time DESC,baseline_id DESC LIMIT ? OFFSET ?", this::baselineView, detectionId, pageSize, (pageNum - 1) * pageSize);
return new BaselinePage(rows, total == null ? 0 : total);
}
long createResult(Actor actor, DetectionView detection, ObservationView observation, Evaluation value,
String inputHash, String requestId) {
ResultView existing = jdbc.query(RESULT_SELECT + " WHERE detection_id=? AND config_version=? AND observation_sha256=?",
this::resultView, detection.detectionId(), detection.version(), observation.payloadSha()).stream().findFirst().orElse(null);
if (existing != null) return existing.resultId();
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO dq_anomaly_result(result_id,detection_id,observation_id,config_version,
observation_sha256,verdict,reason_code,reason_summary,input_summary_sha256,algorithm_code,
algorithm_version,sample_count,lower_bound,upper_bound,fallback_reason,evaluated_at,
organization_id,department_id,create_dept,create_by,create_time,del_flag)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,?,?,?,NOW(),'0')
""", id, detection.detectionId(), observation.observationId(), detection.version(),
observation.payloadSha(), value.verdict().name(), value.reasonCode(), value.reasonSummary(), inputHash,
value.algorithm(), value.algorithmVersion(), value.sampleCount(), value.lower(), value.upper(),
value.fallbackReason(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
} catch (DuplicateKeyException exception) {
return jdbc.queryForObject("SELECT result_id FROM dq_anomaly_result WHERE detection_id=? AND config_version=? AND observation_sha256=?",
Long.class, detection.detectionId(), detection.version(), observation.payloadSha());
}
audit(actor, "RESULT", id, "EVALUATE", null, value.verdict().name(), requestId, value.reasonCode()); return id;
}
ResultView result(long id) { return jdbc.query(RESULT_SELECT + " WHERE result_id=?", this::resultView, id).stream().findFirst().orElseThrow(AnomalyDetectionDomainException::notFound); }
ResultPage results(long detectionId, int pageNum, int pageSize) {
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM dq_anomaly_result WHERE detection_id=?", Long.class, detectionId);
List<ResultView> rows = jdbc.query(RESULT_SELECT + " WHERE detection_id=? ORDER BY evaluated_at DESC,result_id DESC LIMIT ? OFFSET ?", this::resultView, detectionId, pageSize, (pageNum - 1) * pageSize);
return new ResultPage(rows, total == null ? 0 : total);
}
RequestTicket beginRequest(Actor actor, String method, String path, String key, String hash) {
RequestRecord record = request(actor, method, path, key);
if (record != null) return replay(record, hash);
String requestId = IdGeneratorUtil.nextUUID();
try {
jdbc.update("""
INSERT INTO dq_anomaly_request(request_record_id,request_id,actor_id,organization_id,department_id,
request_method,request_path,idempotency_key,request_sha256,request_status,response_object_type,
response_object_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version)
VALUES(?,?,?,?,?,?,?,?,?,'PROCESSING',NULL,NULL,?,?,NOW(),?,NOW(),'0',0)
""", IdGeneratorUtil.nextLongId(), requestId, actor.actorId(), actor.organizationId(), actor.departmentId(),
method, path, key, hash, actor.departmentId(), actor.actorId(), actor.actorId());
return new RequestTicket(requestId, null, null);
} catch (DuplicateKeyException exception) {
RequestRecord raced = request(actor, method, path, key);
if (raced == null) throw AnomalyDetectionDomainException.conflict("幂等请求正在处理中");
return replay(raced, hash);
}
}
void completeRequest(Actor actor, String method, String path, String key, ObjectType type, long objectId) {
int changed = jdbc.update("""
UPDATE dq_anomaly_request SET request_status='COMPLETED',response_object_type=?,response_object_id=?,
update_by=?,update_time=NOW(),version=version+1
WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method=? AND request_path=?
AND idempotency_key=? AND request_status='PROCESSING' AND del_flag='0'
""", type.name(), objectId, actor.actorId(), actor.actorId(), actor.organizationId(), actor.departmentId(),
method, path, key);
requireChanged(changed);
}
private RequestRecord request(Actor actor, String method, String path, String key) {
return jdbc.query("""
SELECT request_id,request_sha256,request_status,response_object_type,response_object_id
FROM dq_anomaly_request WHERE actor_id=? AND organization_id=? AND department_id=?
AND request_method=? AND request_path=? AND idempotency_key=? AND del_flag='0'
""", (rs, n) -> new RequestRecord(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4),
rs.getObject(5, Long.class)), actor.actorId(), actor.organizationId(), actor.departmentId(), method, path, key)
.stream().findFirst().orElse(null);
}
private static RequestTicket replay(RequestRecord value, String hash) {
if (!value.hash().equals(hash)) throw AnomalyDetectionDomainException.conflict("同一幂等键不能用于不同载荷");
if (!"COMPLETED".equals(value.status()) || value.objectId() == null) throw AnomalyDetectionDomainException.conflict("幂等请求仍在处理中");
return new RequestTicket(value.requestId(), ObjectType.valueOf(value.objectType()), value.objectId());
}
private void audit(Actor actor, String type, long id, String action, String before, String after,
String requestId, String summary) {
jdbc.update("""
INSERT INTO dq_anomaly_audit(audit_id,object_type,object_id,action_type,before_status,after_status,
request_id,actor_id,organization_id,department_id,result_summary,create_dept,create_by,create_time,del_flag)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),'0')
""", IdGeneratorUtil.nextLongId(), type, id, action, before, after, requestId, actor.actorId(),
actor.organizationId(), actor.departmentId(), summary, actor.departmentId(), actor.actorId());
}
private DetectionView detectionView(ResultSet rs, int n) throws SQLException {
return new DetectionView(rs.getLong("detection_id"), rs.getString("detection_code"), rs.getString("detection_name"),
DetectionType.valueOf(rs.getString("detection_type")), rs.getString("target_logical_id"), rs.getString("target_fqn"),
rs.getString("expected_schema_fingerprint"), Severity.valueOf(rs.getString("severity_code")),
ThresholdStrategy.valueOf(rs.getString("threshold_strategy")), rs.getBigDecimal("fixed_lower"),
rs.getBigDecimal("fixed_upper"), rs.getInt("minimum_samples"), rs.getInt("history_limit"),
rs.getBigDecimal("deviation_multiplier"), Arrays.stream(rs.getString("allowed_sources").split(","))
.map(SourceType::valueOf).toList(), Status.valueOf(rs.getString("detection_status")),
rs.getLong("organization_id"), rs.getLong("department_id"), rs.getLong("version"),
rs.getObject("create_time", LocalDateTime.class), rs.getObject("update_time", LocalDateTime.class));
}
private ObservationView observationView(ResultSet rs, int n) throws SQLException {
return new ObservationView(rs.getLong("observation_id"), rs.getLong("detection_id"), SourceType.valueOf(rs.getString("source_type")),
rs.getString("external_ref"), rs.getObject("observed_at", LocalDateTime.class), rs.getString("payload_sha256"),
"1".equals(rs.getString("reliable_flag")), rs.getString("unreliable_reason"), rs.getString("schema_fingerprint"),
rs.getObject("row_count", Long.class), bool(rs.getString("empty_batch_flag")), bool(rs.getString("interrupted_flag")),
rs.getBigDecimal("mean_value"), rs.getBigDecimal("stddev_value"), rs.getBigDecimal("minimum_value"),
rs.getBigDecimal("maximum_value"), rs.getBigDecimal("null_ratio"), rs.getObject("data_updated_at", LocalDateTime.class),
rs.getObject("arrived_at", LocalDateTime.class), rs.getObject("processing_delay_seconds", Long.class),
rs.getObject("create_time", LocalDateTime.class));
}
private BaselineView baselineView(ResultSet rs, int n) throws SQLException { return new BaselineView(rs.getLong("baseline_id"), rs.getLong("detection_id"), rs.getString("algorithm_code"), rs.getString("algorithm_version"), rs.getInt("sample_count"), rs.getBigDecimal("lower_bound"), rs.getBigDecimal("upper_bound"), rs.getString("fallback_reason"), rs.getObject("create_time", LocalDateTime.class)); }
private ResultView resultView(ResultSet rs, int n) throws SQLException { return new ResultView(rs.getLong("result_id"), rs.getLong("detection_id"), rs.getLong("observation_id"), rs.getLong("config_version"), rs.getString("observation_sha256"), Verdict.valueOf(rs.getString("verdict")), rs.getString("reason_code"), rs.getString("reason_summary"), rs.getString("input_summary_sha256"), rs.getString("algorithm_code"), rs.getString("algorithm_version"), rs.getObject("sample_count", Integer.class), rs.getBigDecimal("lower_bound"), rs.getBigDecimal("upper_bound"), rs.getString("fallback_reason"), rs.getObject("evaluated_at", LocalDateTime.class)); }
private static String flag(Boolean value) { return value == null ? null : value ? "1" : "0"; }
private static Boolean bool(String value) { return value == null ? null : "1".equals(value); }
private static void requireChanged(int changed) { if (changed != 1) throw AnomalyDetectionDomainException.conflict("版本已变化,请刷新后重试"); }
enum ObjectType { DETECTION, OBSERVATION, BASELINE, RESULT }
record RequestTicket(String requestId, ObjectType objectType, Long objectId) { }
private record RequestRecord(String requestId, String hash, String status, String objectType, Long objectId) { }
record DetectionPage(List<DetectionView> rows, long total) { }
record ObservationPage(List<ObservationView> rows, long total) { }
record BaselinePage(List<BaselineView> rows, long total) { }
record ResultPage(List<ResultView> rows, long total) { }
}
@@ -0,0 +1,339 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.regex.Pattern;
@Component
@RequiredArgsConstructor
class AnomalyDetectionPolicy {
static final String BASELINE_ALGORITHM = "MEDIAN_MAD";
static final String BASELINE_VERSION = "1.0";
static final int MAX_HISTORY = 200;
static final int MAX_AGE_DAYS = 366;
private static final Pattern CODE = Pattern.compile("[A-Z][A-Z0-9_]{1,63}");
private static final Pattern FQN = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:-]{0,511}");
private static final Pattern LOGICAL_ID = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}");
private static final Pattern SHA256 = Pattern.compile("[a-fA-F0-9]{64}");
private static final Pattern SAFE_REF = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:/-]{0,255}");
private static final Pattern DANGEROUS = Pattern.compile(
"(?is).*(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|CREATE|CALL|EXEC|SCRIPT|SHELL)\\b|"
+ "https?://|jdbc:|password|secret|token|credential).*"
);
private final JsonMapper mapper;
String keyword(String value) { return value == null || value.isBlank() ? null : required(value, "查询关键词", 200); }
int pageNum(Integer value) { return bounded(value == null ? 1 : value, 1, 100_000, "页码"); }
int pageSize(Integer value) { return bounded(value == null ? 20 : value, 1, 200, "每页条数"); }
String idempotencyKey(String value) {
if (value == null || !value.matches("[A-Za-z0-9._:-]{8,128}"))
throw AnomalyDetectionDomainException.validation("Idempotency-Key格式无效");
return value;
}
NormalizedDetection normalize(CreateCommand value) {
if (value == null || value.detectionType() == null || value.severity() == null
|| value.thresholdStrategy() == null) {
throw AnomalyDetectionDomainException.validation("异常检测创建请求不完整");
}
return normalizeDetection(code(value.detectionCode()), required(value.detectionName(), "检测名称", 200),
value.detectionType(), value.targetLogicalId(), value.targetFqn(), value.expectedSchemaFingerprint(),
value.severity(), value.thresholdStrategy(), value.fixedLower(), value.fixedUpper(),
value.minimumSamples(), value.historyLimit(), value.deviationMultiplier(), value.allowedSources(), null);
}
NormalizedDetection normalize(UpdateCommand value, DetectionType immutableType) {
if (value == null || value.severity() == null || value.thresholdStrategy() == null
|| value.version() == null || value.version() < 0) {
throw AnomalyDetectionDomainException.validation("异常检测更新请求不完整");
}
return normalizeDetection(null, required(value.detectionName(), "检测名称", 200), immutableType,
value.targetLogicalId(), value.targetFqn(), value.expectedSchemaFingerprint(), value.severity(),
value.thresholdStrategy(), value.fixedLower(), value.fixedUpper(), value.minimumSamples(),
value.historyLimit(), value.deviationMultiplier(), value.allowedSources(), value.version());
}
StatusCommand normalize(StatusCommand value) {
if (value == null || value.targetStatus() == null || value.version() == null || value.version() < 0) {
throw AnomalyDetectionDomainException.validation("状态变更请求不完整");
}
return new StatusCommand(value.targetStatus(), required(value.reason(), "状态变更原因", 500), value.version());
}
ObservationCommand normalize(ObservationCommand value, DetectionView detection, LocalDateTime now) {
if (value == null || value.sourceType() == null || value.observedAt() == null || value.version() == null
|| value.version() < 0) {
throw AnomalyDetectionDomainException.validation("观测请求不完整");
}
if (!detection.allowedSources().contains(value.sourceType())) {
throw AnomalyDetectionDomainException.validation("观测来源不在检测配置白名单");
}
if (value.observedAt().isAfter(now.plusMinutes(5)) || value.observedAt().isBefore(now.minusDays(MAX_AGE_DAYS))) {
throw AnomalyDetectionDomainException.validation("观测时间超出允许窗口");
}
String reason = value.reliable() ? null : required(value.unreliableReason(), "不可靠原因", 500);
ObservationCommand normalized = new ObservationCommand(value.sourceType(), safeRef(value.externalRef()),
value.observedAt(), sha(value.payloadSha()), value.reliable(), reason,
optionalSha(value.schemaFingerprint()), nonNegative(value.rowCount(), "行数"), value.emptyBatch(),
value.interrupted(), decimal(value.mean(), "均值", true), decimal(value.standardDeviation(), "标准差", true),
decimal(value.minimum(), "最小值", true), decimal(value.maximum(), "最大值", true),
ratio(value.nullRatio()), value.dataUpdatedAt(), value.arrivedAt(),
nonNegative(value.processingDelaySeconds(), "处理延迟"), value.version());
requireTypePayload(detection.detectionType(), normalized);
return normalized;
}
BaselineCalculation baseline(List<BigDecimal> rawSamples, int minimumSamples, BigDecimal multiplier) {
List<BigDecimal> samples = rawSamples == null ? List.of() : rawSamples.stream()
.filter(Objects::nonNull).map(v -> decimal(v, "历史样本", false)).sorted().toList();
if (samples.size() < minimumSamples) {
return new BaselineCalculation(BASELINE_ALGORITHM, BASELINE_VERSION, samples.size(), null, null,
"INSUFFICIENT_SAMPLES");
}
BigDecimal median = median(samples);
List<BigDecimal> deviations = samples.stream().map(v -> v.subtract(median).abs()).sorted().toList();
BigDecimal mad = median(deviations);
BigDecimal span = mad.multiply(new BigDecimal("1.4826")).multiply(multiplier)
.setScale(6, RoundingMode.HALF_UP);
return new BaselineCalculation(BASELINE_ALGORITHM, BASELINE_VERSION, samples.size(),
median.subtract(span).setScale(6, RoundingMode.HALF_UP),
median.add(span).setScale(6, RoundingMode.HALF_UP), mad.signum() == 0 ? "ZERO_MAD" : null);
}
Evaluation evaluate(DetectionView detection, ObservationView observation, BaselineView baseline,
LocalDateTime now) {
if (!observation.reliable()) return unknown("UNRELIABLE_EVIDENCE", observation.unreliableReason(), baseline);
if (observation.observedAt().isAfter(now.plusMinutes(5))) {
return unknown("TIME_INVERSION", "观测时间晚于评估时间", baseline);
}
Bounds bounds = bounds(detection, baseline);
if (detection.thresholdStrategy() == ThresholdStrategy.BASELINE && !bounds.available()) {
return unknown("INSUFFICIENT_BASELINE", baseline == null ? "未生成历史基线" : baseline.fallbackReason(), baseline);
}
return switch (detection.detectionType()) {
case SCHEMA -> verdict(Objects.equals(detection.expectedSchemaFingerprint(), observation.schemaFingerprint()),
"SCHEMA_MATCH", "SCHEMA_CHANGED", baseline);
case VOLUME -> {
if (Boolean.TRUE.equals(observation.emptyBatch()) || Boolean.TRUE.equals(observation.interrupted())) {
yield anomaly("VOLUME_FLOW_INTERRUPTED", "空批次或断流标记", baseline);
}
yield numeric(observation.rowCount() == null ? null : BigDecimal.valueOf(observation.rowCount()),
bounds, "VOLUME", baseline);
}
case DISTRIBUTION -> numeric(observation.mean(), bounds, "DISTRIBUTION", baseline);
case FRESHNESS -> {
if (observation.dataUpdatedAt() == null || observation.arrivedAt() == null
|| observation.dataUpdatedAt().isAfter(observation.arrivedAt())) {
yield unknown("TIME_INVERSION", "数据更新时间与到达时间缺失或倒置", baseline);
}
long freshnessSeconds = observation.arrivedAt().toEpochSecond(ZoneOffset.UTC)
- observation.dataUpdatedAt().toEpochSecond(ZoneOffset.UTC);
long effective = Math.max(freshnessSeconds,
observation.processingDelaySeconds() == null ? 0 : observation.processingDelaySeconds());
yield numeric(BigDecimal.valueOf(effective), bounds, "FRESHNESS", baseline);
}
};
}
BigDecimal sampleValue(DetectionType type, ObservationView value) {
return switch (type) {
case VOLUME -> value.rowCount() == null ? null : BigDecimal.valueOf(value.rowCount());
case DISTRIBUTION -> value.mean();
case FRESHNESS -> value.dataUpdatedAt() == null || value.arrivedAt() == null
|| value.dataUpdatedAt().isAfter(value.arrivedAt()) ? null
: BigDecimal.valueOf(Math.max(value.arrivedAt().toEpochSecond(ZoneOffset.UTC)
- value.dataUpdatedAt().toEpochSecond(ZoneOffset.UTC),
value.processingDelaySeconds() == null ? 0 : value.processingDelaySeconds()));
case SCHEMA -> null;
};
}
String requestHash(Object value) { return sha256(write(value)); }
String inputSummaryHash(Object value) { return sha256(write(value)); }
private NormalizedDetection normalizeDetection(String code, String name, DetectionType type,
String logicalId, String fqn, String expectedFingerprint,
Severity severity, ThresholdStrategy strategy,
BigDecimal lower, BigDecimal upper, Integer minimumSamples,
Integer historyLimit, BigDecimal multiplier,
List<SourceType> sources, Long version) {
String fingerprint = optionalSha(expectedFingerprint);
if (type == DetectionType.SCHEMA && fingerprint == null) {
throw AnomalyDetectionDomainException.validation("Schema检测必须提供期望指纹");
}
if (type != DetectionType.SCHEMA && fingerprint != null) {
throw AnomalyDetectionDomainException.validation("非Schema检测不得提供Schema指纹");
}
int min = bounded(minimumSamples == null ? 5 : minimumSamples, 3, 50, "最小样本数");
int history = bounded(historyLimit == null ? 30 : historyLimit, min, MAX_HISTORY, "历史样本上限");
BigDecimal factor = multiplier == null ? new BigDecimal("3.0000") : decimal(multiplier, "偏差倍数", false);
if (factor.compareTo(new BigDecimal("0.1000")) < 0 || factor.compareTo(new BigDecimal("10.0000")) > 0) {
throw AnomalyDetectionDomainException.validation("偏差倍数必须在0.1到10之间");
}
BigDecimal normalizedLower = decimal(lower, "固定下界", true);
BigDecimal normalizedUpper = decimal(upper, "固定上界", true);
if (strategy == ThresholdStrategy.FIXED && type != DetectionType.SCHEMA && normalizedLower == null
&& normalizedUpper == null) {
throw AnomalyDetectionDomainException.validation("固定阈值至少需要一个上下界");
}
if (normalizedLower != null && normalizedUpper != null && normalizedLower.compareTo(normalizedUpper) > 0) {
throw AnomalyDetectionDomainException.validation("固定阈值下界不得高于上界");
}
List<SourceType> allowed = sources == null ? List.of() : sources.stream().filter(Objects::nonNull).distinct().toList();
if (allowed.isEmpty() || allowed.size() > SourceType.values().length) {
throw AnomalyDetectionDomainException.validation("必须配置1至5个观测来源白名单");
}
return new NormalizedDetection(code, name, type, logicalId(logicalId), fqn(fqn), fingerprint, severity,
strategy, normalizedLower, normalizedUpper, min, history, factor, allowed,
allowed.stream().map(Enum::name).sorted().reduce((a, b) -> a + "," + b).orElseThrow(), version);
}
private static void requireTypePayload(DetectionType type, ObservationCommand value) {
boolean valid = switch (type) {
case SCHEMA -> value.schemaFingerprint() != null && value.rowCount() == null && value.mean() == null
&& value.dataUpdatedAt() == null;
case VOLUME -> value.rowCount() != null && value.schemaFingerprint() == null && value.mean() == null
&& value.dataUpdatedAt() == null;
case DISTRIBUTION -> value.mean() != null && value.standardDeviation() != null
&& value.minimum() != null && value.maximum() != null && value.nullRatio() != null
&& value.minimum().compareTo(value.maximum()) <= 0 && value.schemaFingerprint() == null
&& value.rowCount() == null && value.dataUpdatedAt() == null;
case FRESHNESS -> value.dataUpdatedAt() != null && value.arrivedAt() != null
&& value.processingDelaySeconds() != null && value.schemaFingerprint() == null
&& value.rowCount() == null && value.mean() == null;
};
if (!valid) throw AnomalyDetectionDomainException.validation("观测字段不符合检测类型白名单");
}
private static Bounds bounds(DetectionView detection, BaselineView baseline) {
if (detection.detectionType() == DetectionType.SCHEMA) return new Bounds(null, null);
return detection.thresholdStrategy() == ThresholdStrategy.FIXED
? new Bounds(detection.fixedLower(), detection.fixedUpper())
: baseline == null ? new Bounds(null, null) : new Bounds(baseline.lowerBound(), baseline.upperBound());
}
private static Evaluation numeric(BigDecimal value, Bounds bounds, String prefix, BaselineView baseline) {
if (value == null) return unknown("MISSING_EVIDENCE", prefix + "观测值缺失", baseline);
boolean low = bounds.lower() != null && value.compareTo(bounds.lower()) < 0;
boolean high = bounds.upper() != null && value.compareTo(bounds.upper()) > 0;
return low || high ? anomaly(prefix + "_OUT_OF_BOUNDS", "观测值超出确定阈值", baseline)
: normal(prefix + "_WITHIN_BOUNDS", "观测值位于确定阈值内", baseline);
}
private static Evaluation verdict(boolean normal, String normalCode, String anomalyCode, BaselineView baseline) {
return normal ? normal(normalCode, "结构指纹一致", baseline) : anomaly(anomalyCode, "结构指纹发生变化", baseline);
}
private static Evaluation normal(String code, String summary, BaselineView b) { return evaluation(Verdict.NORMAL, code, summary, b); }
private static Evaluation anomaly(String code, String summary, BaselineView b) { return evaluation(Verdict.ANOMALY, code, summary, b); }
private static Evaluation unknown(String code, String summary, BaselineView b) { return evaluation(Verdict.UNKNOWN, code, summary, b); }
private static Evaluation evaluation(Verdict verdict, String code, String summary, BaselineView b) {
return new Evaluation(verdict, code, summary == null ? code : summary,
b == null ? "FIXED" : b.algorithm(), b == null ? "1.0" : b.algorithmVersion(),
b == null ? null : b.sampleCount(), b == null ? null : b.lowerBound(),
b == null ? null : b.upperBound(), b == null ? null : b.fallbackReason());
}
private static BigDecimal median(List<BigDecimal> values) {
int middle = values.size() / 2;
return values.size() % 2 == 1 ? values.get(middle)
: values.get(middle - 1).add(values.get(middle)).divide(BigDecimal.valueOf(2), 6, RoundingMode.HALF_UP);
}
private String write(Object value) {
try { return mapper.writeValueAsString(value); }
catch (JacksonException exception) { throw AnomalyDetectionDomainException.validation("请求无法序列化"); }
}
private static String code(String value) {
String normalized = value == null ? null : value.trim().toUpperCase(Locale.ROOT);
if (normalized == null || !CODE.matcher(normalized).matches()) throw AnomalyDetectionDomainException.validation("检测编码格式无效");
return normalized;
}
private static String logicalId(String value) {
String normalized = required(value, "目标逻辑ID", 128);
if (!LOGICAL_ID.matcher(normalized).matches()) throw AnomalyDetectionDomainException.validation("目标逻辑ID格式无效");
return normalized;
}
private static String fqn(String value) {
String normalized = required(value, "目标FQN", 512);
if (!FQN.matcher(normalized).matches()) throw AnomalyDetectionDomainException.validation("目标FQN格式无效");
return normalized;
}
private static String safeRef(String value) {
String normalized = required(value, "外部引用", 256);
if (!SAFE_REF.matcher(normalized).matches() || DANGEROUS.matcher(normalized).matches()) {
throw AnomalyDetectionDomainException.validation("外部引用格式无效");
}
return normalized;
}
private static String sha(String value) {
String normalized = required(value, "payloadSha", 64).toLowerCase(Locale.ROOT);
if (!SHA256.matcher(normalized).matches()) throw AnomalyDetectionDomainException.validation("payloadSha必须是SHA-256");
return normalized;
}
private static String optionalSha(String value) { return value == null || value.isBlank() ? null : sha(value); }
private static String required(String value, String label, int max) {
if (value == null || value.isBlank()) throw AnomalyDetectionDomainException.validation(label + "不能为空");
String normalized = value.trim();
if (normalized.length() > max || DANGEROUS.matcher(normalized).matches()) {
throw AnomalyDetectionDomainException.validation(label + "包含禁用内容或超出长度");
}
return normalized;
}
private static Long nonNegative(Long value, String label) {
if (value != null && value < 0) throw AnomalyDetectionDomainException.validation(label + "不得为负数");
return value;
}
private static BigDecimal ratio(BigDecimal value) {
BigDecimal normalized = decimal(value, "空值率", true);
if (normalized != null && (normalized.signum() < 0 || normalized.compareTo(BigDecimal.ONE) > 0)) {
throw AnomalyDetectionDomainException.validation("空值率必须在0到1之间");
}
return normalized;
}
private static BigDecimal decimal(BigDecimal value, String label, boolean nullable) {
if (value == null) {
if (nullable) return null;
throw AnomalyDetectionDomainException.validation(label + "不能为空");
}
if (value.precision() > 24 || value.scale() > 6) throw AnomalyDetectionDomainException.validation(label + "超出数值精度");
return value.setScale(6, RoundingMode.UNNECESSARY);
}
private static int bounded(int value, int min, int max, String label) {
if (value < min || value > max) throw AnomalyDetectionDomainException.validation(label + "超出范围");
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); }
}
record NormalizedDetection(String detectionCode, String detectionName, DetectionType detectionType,
String targetLogicalId, String targetFqn, String expectedSchemaFingerprint,
Severity severity, ThresholdStrategy thresholdStrategy, BigDecimal fixedLower,
BigDecimal fixedUpper, int minimumSamples, int historyLimit,
BigDecimal deviationMultiplier, List<SourceType> allowedSources,
String allowedSourcesCsv, Long version) { }
record BaselineCalculation(String algorithm, String version, int sampleCount, BigDecimal lower,
BigDecimal upper, String fallbackReason) { }
record Evaluation(Verdict verdict, String reasonCode, String reasonSummary, String algorithm,
String algorithmVersion, Integer sampleCount, BigDecimal lower, BigDecimal upper,
String fallbackReason) { }
private record Bounds(BigDecimal lower, BigDecimal upper) {
boolean available() { return lower != null || upper != null; }
}
}
@@ -0,0 +1,183 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionActorProvider.Actor;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionApi.*;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionJdbcRepository.ObjectType;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionJdbcRepository.RequestTicket;
import cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionPolicy.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
@Service
@RequiredArgsConstructor
class AnomalyDetectionService {
private static final String ROOT = "/api/governance/v1/anomaly-detections";
private final AnomalyDetectionJdbcRepository repository;
private final cn.aixunkeji.datagov.governance.qualityissue.QualityIssueCandidates identityCandidates;
private final AnomalyDetectionPolicy policy;
private final AnomalyDetectionActorProvider actorProvider;
private final TransactionTemplate transactions;
private final AnomalyProfileTargetService profileTargets;
PageResult<DetectionView> page(String keyword, DetectionType type, Status status, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var page = repository.page(actor, policy.keyword(keyword), type, status, policy.pageNum(pageNum), policy.pageSize(pageSize));
return PageResult.build(page.rows(), page.total());
}
DetectionView detail(long id) { return repository.detection(positive(id), actorProvider.current()); }
WriteView<DetectionView> create(String rawKey, CreateCommand raw) {
Actor actor = actorProvider.current();
if (raw != null && raw.detectionType() == DetectionType.SCHEMA)
throw AnomalyDetectionDomainException.conflict("暂无可确认的结构基线,请先完成基线接入");
NormalizedDetection command = policy.normalize(raw);
ProfileTargetSelection selection=raw.profileTarget();if(selection!=null)profileTargets.requireWrite(actor,false);
var result=execute(actor, "POST", ROOT, rawKey, selection==null?command:new TargetWrite(command,selection), ObjectType.DETECTION,
requestId -> { requireTarget(actor,command,selection);long id=repository.create(actor, command, requestId);
if(selection!=null){profileTargets.require(selection,command);profileTargets.requireWrite(actor,false);}return id; }, id -> repository.detection(id, actor));
if(selection!=null)profileTargets.requireWrite(actor,false);return result;
}
WriteView<DetectionView> update(long rawId, String rawKey, UpdateCommand raw) {
long id = positive(rawId); Actor actor = actorProvider.current();
ProfileTargetSelection selection=raw==null?null:raw.profileTarget();
DetectionView current = repository.detection(id, actor);
if (current.detectionType() == DetectionType.SCHEMA) {
if(raw==null || !java.util.Objects.equals(raw.targetLogicalId(),current.targetLogicalId())
|| !java.util.Objects.equals(raw.targetFqn(),current.targetFqn())
|| raw.expectedSchemaFingerprint()!=null && !raw.expectedSchemaFingerprint().equals(current.expectedSchemaFingerprint()))
throw AnomalyDetectionDomainException.conflict("结构基线不可覆盖,请先完成基线接入");
raw=new UpdateCommand(raw.detectionName(),current.targetLogicalId(),current.targetFqn(),current.expectedSchemaFingerprint(),
raw.severity(),raw.thresholdStrategy(),raw.fixedLower(),raw.fixedUpper(),raw.minimumSamples(),raw.historyLimit(),
raw.deviationMultiplier(),raw.allowedSources(),raw.version());
}
NormalizedDetection command = policy.normalize(raw, current.detectionType());
if(selection!=null)profileTargets.requireWrite(actor,true);
var result=execute(actor, "PUT", ROOT + '/' + id, rawKey, selection==null?command:new TargetWrite(command,selection), ObjectType.DETECTION, requestId -> {
requireVersion(repository.detection(id, actor).version(), command.version());
requireTarget(actor,command,selection);
repository.update(actor, id, command, requestId);
if(selection!=null){profileTargets.require(selection,command);profileTargets.requireWrite(actor,true);}return id;
}, value -> repository.detection(value, actor));
if(selection!=null)profileTargets.requireWrite(actor,true);return result;
}
WriteView<DetectionView> status(long rawId, String rawKey, StatusCommand raw) {
long id = positive(rawId); Actor actor = actorProvider.current(); StatusCommand command = policy.normalize(raw);
return execute(actor, "POST", ROOT + '/' + id + "/status", rawKey, command, ObjectType.DETECTION, requestId -> {
DetectionView current = repository.detection(id, actor); requireVersion(current.version(), command.version());
if (current.status() == command.targetStatus()) throw AnomalyDetectionDomainException.conflict("状态未变化");
repository.status(actor, id, current.status(), command, requestId); return id;
}, value -> repository.detection(value, actor));
}
PageResult<ObservationView> observations(long rawId, Integer pageNum, Integer pageSize) {
long id = positive(rawId); Actor actor = actorProvider.current(); repository.detection(id, actor);
var page = repository.observations(id, policy.pageNum(pageNum), policy.pageSize(pageSize));
return PageResult.build(page.rows(), page.total());
}
WriteView<ObservationView> observe(long rawId, String rawKey, ObservationCommand raw) {
if(raw!=null&&raw.reliable())throw AnomalyDetectionDomainException.validation("手工观测不能标为可信,请使用真实画像序列登记评估");
long id = positive(rawId); Actor actor = actorProvider.current(); DetectionView detection = repository.detection(id, actor);
requireVersion(detection.version(), raw == null ? null : raw.version());
ObservationCommand command = policy.normalize(raw, detection, LocalDateTime.now());
return execute(actor, "POST", ROOT + '/' + id + "/observations", rawKey, command, ObjectType.OBSERVATION,
requestId -> repository.createObservation(actor, id, command, requestId), repository::observation);
}
WriteView<BaselineView> baseline(long rawId, String rawKey, BaselineCommand raw) {
long id = positive(rawId); Actor actor = actorProvider.current(); DetectionView detection = repository.detection(id, actor);
if (raw == null || raw.version() == null) throw AnomalyDetectionDomainException.validation("基线请求不完整");
requireVersion(detection.version(), raw.version());
if (detection.thresholdStrategy() != ThresholdStrategy.BASELINE || detection.detectionType() == DetectionType.SCHEMA) {
throw AnomalyDetectionDomainException.conflict("当前检测类型或策略不生成数值历史基线");
}
if (raw.sampleCount() != null && (raw.sampleCount() < detection.minimumSamples()
|| raw.sampleCount() > detection.historyLimit())) {
throw AnomalyDetectionDomainException.validation("基线样本数必须位于配置的最小样本数和历史上限之间");
}
int count = raw.sampleCount() == null ? detection.historyLimit() : raw.sampleCount();
List<ObservationView> observations = repository.recentReliableObservations(id, count);
BaselineCalculation calculation = policy.baseline(observations.stream()
.map(value -> policy.sampleValue(detection.detectionType(), value)).toList(),
detection.minimumSamples(), detection.deviationMultiplier());
return execute(actor, "POST", ROOT + '/' + id + "/baselines", rawKey,
new BaselinePayload(raw, calculation), ObjectType.BASELINE,
requestId -> repository.createBaseline(actor, id, calculation, requestId), repository::baseline);
}
PageResult<BaselineView> baselines(long rawId, Integer pageNum, Integer pageSize) {
long id = positive(rawId); Actor actor = actorProvider.current(); repository.detection(id, actor);
var page = repository.baselines(id, policy.pageNum(pageNum), policy.pageSize(pageSize));
return PageResult.build(page.rows(), page.total());
}
WriteView<ResultView> evaluate(long rawId, String rawKey, EvaluateCommand command) {
long id = positive(rawId); Actor actor = actorProvider.current(); DetectionView detection = repository.detection(id, actor);
if (command == null || command.observationId() <= 0 || command.version() == null) {
throw AnomalyDetectionDomainException.validation("评估请求不完整");
}
requireVersion(detection.version(), command.version());
if (detection.status() != Status.ENABLED) throw AnomalyDetectionDomainException.conflict("停用检测不可评估");
ObservationView observation = repository.observationForDetection(command.observationId(), id);
BaselineView baseline = detection.thresholdStrategy() == ThresholdStrategy.BASELINE ? repository.latestBaseline(id) : null;
Evaluation evaluation = policy.evaluate(detection, observation, baseline, LocalDateTime.now());
String inputHash = policy.inputSummaryHash(Arrays.asList(detection.detectionType(), detection.version(),
observation.payloadSha(), evaluation.algorithm(), evaluation.algorithmVersion(), evaluation.lower(), evaluation.upper()));
return execute(actor, "POST", ROOT + '/' + id + "/evaluate", rawKey,
new EvaluationPayload(command, inputHash), ObjectType.RESULT,
requestId -> repository.createResult(actor, detection, observation, evaluation, inputHash, requestId),
repository::result);
}
PageResult<ResultView> results(long rawId, Integer pageNum, Integer pageSize) {
long id = positive(rawId); Actor actor = actorProvider.current(); repository.detection(id, actor);
var page = repository.results(id, policy.pageNum(pageNum), policy.pageSize(pageSize));
return PageResult.build(page.rows(), page.total());
}
private <T> WriteView<T> execute(Actor actor, String method, String path, String rawKey, Object command,
ObjectType type, Function<String, Long> mutation, Function<Long, T> reader) {
String key = policy.idempotencyKey(rawKey); String hash = policy.requestHash(command);
Completion completion = inTransaction(() -> {
RequestTicket ticket = repository.beginRequest(actor, method, path, key, hash);
if (ticket.objectId() != null) {
if (ticket.objectType() != type) throw AnomalyDetectionDomainException.conflict("幂等结果类型不一致");
return new Completion(ticket.requestId(), ticket.objectId());
}
long objectId = mutation.apply(ticket.requestId());
repository.completeRequest(actor, method, path, key, type, objectId);
return new Completion(ticket.requestId(), objectId);
});
return new WriteView<>(completion.requestId(), reader.apply(completion.objectId()));
}
private void requireTarget(Actor actor,NormalizedDetection command,ProfileTargetSelection selection){
if(selection==null)identityCandidates.requireTarget(actor.organizationId(),actor.departmentId(),command.targetLogicalId(),command.targetFqn());
else profileTargets.require(selection,command);
}
private record TargetWrite(NormalizedDetection command,ProfileTargetSelection profileTarget) { }
private <T> T inTransaction(Supplier<T> action) {
T result = transactions.execute(status -> action.get());
if (result == null) throw new IllegalStateException("异常检测事务未返回结果");
return result;
}
private static long positive(long id) {
if (id <= 0) throw AnomalyDetectionDomainException.validation("异常检测ID无效"); return id;
}
private static void requireVersion(long current, Long expected) {
if (expected == null || current != expected) throw AnomalyDetectionDomainException.conflict("版本已变化,请刷新后重试");
}
private record Completion(String requestId, long objectId) { }
private record BaselinePayload(BaselineCommand command, BaselineCalculation calculation) { }
private record EvaluationPayload(EvaluateCommand command, String inputHash) { }
}
@@ -0,0 +1,48 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.api.qualityissue.QualityIssueAssistDirectory.*;
import cn.aixunkeji.datagov.governance.qualityissue.QualityIssueEvidenceException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import tools.jackson.databind.ObjectMapper;
import java.time.LocalDateTime;
import java.util.*;
/** Reads only this Owner's stored evaluations; no raw statistics leave the Owner. */
@Service @RequiredArgsConstructor
public class AnomalyIssueEvidence {
private final AnomalyDetectionJdbcRepository repository;private final AnomalyDetectionActorProvider actors;private final ObjectMapper json;
@org.springframework.beans.factory.annotation.Autowired private AnomalySourceEvidence trusted;
public List<Option> candidates(String keyword){
try {
if(keyword!=null&&(keyword.length()>100||keyword.indexOf('\0')>=0))throw AnomalyDetectionDomainException.validation("检查名称过长或无效");
return repository.issueEvidenceCandidates(actors.current(),keyword==null||keyword.isBlank()?null:keyword.trim());
} catch (AnomalyDetectionDomainException rejected) { throw sourceFailure(rejected); }
}
public Evidence current(Selection selection){
try { return read(selection); }
catch (AnomalyDetectionDomainException rejected) { throw sourceFailure(rejected); }
catch (cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner.SourceException rejected) {
throw new QualityIssueEvidenceException(rejected.code(),rejected.status(),rejected.getMessage());
}
}
private Evidence read(Selection selection){
if(!TransactionSynchronizationManager.isActualTransactionActive())throw new IllegalStateException("Evidence reads require an Owner transaction");
var actor=actors.current();var d=repository.lockIssueDetection(selection.detectionId(),actor);
var r=repository.lockIssueResult(selection.resultId(),d.detectionId());var o=repository.lockIssueObservation(r.observationId(),d.detectionId());
if(d.version()!=selection.configVersion()||r.configVersion()!=d.version()||r.verdict()!=AnomalyDetectionApi.Verdict.ANOMALY
||!o.reliable()||!Objects.equals(r.observationSha(),o.payloadSha())||r.observationSha()==null||!r.observationSha().matches("[a-fA-F0-9]{64}")
||r.inputSummarySha()==null||!r.inputSummarySha().matches("[a-fA-F0-9]{64}")||r.evaluatedAt()==null
||r.evaluatedAt().isAfter(LocalDateTime.now().plusMinutes(5))||r.evaluatedAt().isBefore(LocalDateTime.now().minusDays(366)))
throw AnomalyDetectionDomainException.conflict("检查配置、结果或观测已变化,请重新选择已登记的异常评估");
var proof=trusted.current(r.resultId());
if(!Long.toString(d.detectionId()).equals(proof.detectionId())||proof.configVersion()!=d.version()||!"ANOMALY".equals(proof.verdict()))throw AnomalySourceEvidence.invalid();
if(!actor.equals(actors.current()))throw AnomalyDetectionDomainException.forbidden();
return new Evidence(d.detectionName(),d.targetLogicalId(),d.targetFqn(),d.severity().name(),r.reasonCode(),r.evaluatedAt().toString(),
proof.evidenceSha(),"REGISTERED_EVALUATION");
}
private static QualityIssueEvidenceException sourceFailure(AnomalyDetectionDomainException rejected) {
return new QualityIssueEvidenceException(rejected.code(),rejected.status(),rejected.getMessage());
}
private static String sha(String text){try{return HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes(java.nio.charset.StandardCharsets.UTF_8)));}catch(java.security.NoSuchAlgorithmException impossible){throw new IllegalStateException(impossible);}}
}
@@ -0,0 +1,19 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory.Choice;
import cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController @RequiredArgsConstructor @RequestMapping("/api/governance/v1/anomaly-detections/assist")
class AnomalyProfileTargetController {
record Selection(String snapshotId) { }
private final AnomalyProfileTargetService service;
@GetMapping("/target-profiles") @SaCheckPermission("aixun:governance:anomaly-detection:view") R<java.util.List<Choice>> choices(){return R.ok(service.choices());}
@PostMapping("/target") @SaCheckPermission("aixun:governance:anomaly-detection:view") R<ProfileSeriesOwner.Target> current(@RequestBody Selection value){if(value==null)throw AnomalyDetectionDomainException.validation("请选择已绑定画像");return R.ok(service.current(value.snapshotId()));}
@ExceptionHandler(AnomalyDetectionDomainException.class) ResponseEntity<R<Void>> domain(AnomalyDetectionDomainException e){return ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
@ExceptionHandler(ProfileSeriesOwner.SourceException.class) ResponseEntity<R<Void>> source(ProfileSeriesOwner.SourceException e){return ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
}
@@ -0,0 +1,22 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory.Choice;
import cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import static cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionApi.*;
@Service @RequiredArgsConstructor
class AnomalyProfileTargetService {
private final AnomalyDetectionActorProvider actors;private final AnomalySeriesAuthority authority;private final ProfileSeriesOwner profiles;
List<Choice> choices(){var actor=actors.current();authority.require(actor,false);var result=profiles.choices();authority.require(actor,false);return result;}
ProfileSeriesOwner.Target current(String snapshotId){long id=AnomalySeriesPolicy.id(snapshotId);var actor=actors.current();authority.require(actor,false);var result=profiles.target(id);authority.require(actor,false);return result;}
void requireWrite(AnomalyDetectionActorProvider.Actor actor,boolean update){authority.requireWrite(actor,update);}
void require(ProfileTargetSelection selection,AnomalyDetectionPolicy.NormalizedDetection command){
if(selection==null||command.detectionType()!=DetectionType.VOLUME||selection.fingerprint()==null||!selection.fingerprint().matches("[0-9a-f]{64}"))throw AnomalyDetectionDomainException.validation("请选择已核对的表行数目标");
var target=current(selection.snapshotId());
if(!selection.snapshotId().equals(target.snapshotId())||!selection.fingerprint().equals(target.fingerprint())||!command.targetLogicalId().equals(target.targetLogicalId())||!command.targetFqn().equals(target.targetFqn()))
throw AnomalyDetectionDomainException.conflict("目标来源、结构或权限已变化,请重新选择");
}
}
@@ -0,0 +1,15 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.time.Instant;
@Component
class AnomalySeriesAuthority {
private final AnomalyDetectionActorProvider actors;
@DubboReference(check=false,timeout=3000,retries=0)private RemoteUserService users;
AnomalySeriesAuthority(AnomalyDetectionActorProvider actors){this.actors=actors;}
void require(AnomalyDetectionActorProvider.Actor actor,boolean ai){if(!actor.equals(actors.current()))throw AnomalyDetectionDomainException.forbidden();check(actor,"ANOMALY_SERIES_VIEW");if(ai)check(actor,"PAGE_AI_P57");if(!actor.equals(actors.current()))throw AnomalyDetectionDomainException.forbidden();}
void requireWrite(AnomalyDetectionActorProvider.Actor actor,boolean update){require(actor,false);check(actor,update?"ANOMALY_TARGET_UPDATE":"ANOMALY_TARGET_CREATE");if(!actor.equals(actors.current()))throw AnomalyDetectionDomainException.forbidden();}
void requireEvaluation(AnomalyDetectionActorProvider.Actor actor){require(actor,false);check(actor,"ANOMALY_SERIES_EVALUATE");if(!actor.equals(actors.current()))throw AnomalyDetectionDomainException.forbidden();}
private void check(AnomalyDetectionActorProvider.Actor actor,String purpose){var now=Instant.now();try{var result=users.resolveAssetActor(actor.actorId(),actor.departmentId(),purpose);if(result!=null&&result.allowed()&&result.userId()==actor.actorId()&&result.deptId()==actor.departmentId()&&purpose.equals(result.purpose())&&result.checkedAt()!=null&&!result.checkedAt().isBefore(now.minusSeconds(10))&&!result.checkedAt().isAfter(now.plusSeconds(5)))return;}catch(RuntimeException unavailable){}throw AnomalyDetectionDomainException.forbidden();}
}
@@ -0,0 +1,23 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory.*;
import cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController @RequiredArgsConstructor @RequestMapping("/api/governance/v1/anomaly-detections/assist")
class AnomalySeriesController {
private final AnomalySeriesService service;
private final AnomalySourceEvidence evidence;
@GetMapping("/{id}/profiles") @SaCheckPermission("aixun:governance:anomaly-detection:view")R<java.util.List<Choice>> choices(@PathVariable long id,@RequestParam long version){return R.ok(service.choices(id,version));}
@PostMapping("/context") @SaCheckPermission("aixun:governance:anomaly-detection:view")R<Context> context(@RequestBody Selection selection){return R.ok(service.current(selection,false));}
@cn.aixunkeji.common.log.annotation.Log(title="登记真实画像异常评估",businessType=cn.aixunkeji.common.log.enums.BusinessType.INSERT,isSaveRequestData=false,isSaveResponseData=false)
@PostMapping("/evaluations") @SaCheckPermission("aixun:governance:anomaly-detection:evaluate")
R<AnomalySourceEvidence.Result> save(@RequestHeader("Idempotency-Key")String key,@RequestBody AnomalySourceEvidence.Save command){return R.ok(evidence.save(key,command));}
@GetMapping("/evaluations/requests/{key}") @SaCheckPermission("aixun:governance:anomaly-detection:evaluate")
R<AnomalySourceEvidence.Result> request(@PathVariable String key){return R.ok(evidence.request(key));}
@ExceptionHandler(AnomalyDetectionDomainException.class)ResponseEntity<R<Void>> domainError(AnomalyDetectionDomainException e){return ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
@ExceptionHandler(ProfileSeriesOwner.SourceException.class)ResponseEntity<R<Void>> sourceError(ProfileSeriesOwner.SourceException e){return ResponseEntity.status(e.status()).body(R.fail(e.code(),e.getMessage()));}
@ExceptionHandler(RuntimeException.class)ResponseEntity<R<Void>> unknown(RuntimeException e){return ResponseEntity.status(503).body(R.fail("结果尚未确认,请读取原请求"));}
}
@@ -0,0 +1,9 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboService;
@RequiredArgsConstructor @DubboService(version=AnomalySeriesDirectory.VERSION,timeout=60000,retries=0)
public class AnomalySeriesDubboService implements AnomalySeriesDirectory {
private final AnomalySeriesService service;
@Override public Context current(Selection selection){return service.current(selection,true);}
}
@@ -0,0 +1,36 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory.*;
import cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner;
import java.math.BigDecimal;
import java.time.*;
import java.util.*;
final class AnomalySeriesPolicy {
private AnomalySeriesPolicy() { }
static Selection normalize(Selection value){
if(value==null||value.version()<0||value.snapshotIds()==null||value.snapshotIds().size()<4||value.snapshotIds().size()>51||new HashSet<>(value.snapshotIds()).size()!=value.snapshotIds().size())throw invalid("请选择4至51个不重复历史画像");
id(value.detectionId());value.snapshotIds().forEach(AnomalySeriesPolicy::id);
var start=time(value.windowStart());var end=time(value.windowEnd());var now=LocalDateTime.now();
if(!start.isBefore(end)||start.isBefore(now.minusDays(366))||end.isAfter(now.plusMinutes(5)))throw invalid("观察时间范围必须位于过去366日,且不能倒置");
return new Selection(value.detectionId(),value.version(),List.copyOf(value.snapshotIds()),value.windowStart(),value.windowEnd());
}
static void config(AnomalyDetectionApi.DetectionView value,Selection selection){if(value.version()!=selection.version())throw AnomalyDetectionDomainException.conflict("检测配置版本已变化");if(value.detectionType()!=AnomalyDetectionApi.DetectionType.VOLUME)throw invalid("当前真实画像历史仅支持表行数,其他检测类型需要对应观察来源");if(selection.snapshotIds().size()<value.minimumSamples()+1||selection.snapshotIds().size()>value.historyLimit()+1)throw invalid("至少需要最小样本数加一个独立观察点,且不能超过历史上限加一");}
static Context calculate(Selection selection,AnomalyDetectionApi.DetectionView config,ProfileSeriesOwner.Series series,AnomalyDetectionPolicy policy){
config(config,selection);if(series==null||series.points()==null||series.points().size()!=selection.snapshotIds().size()||!config.allowedSources().stream().map(Enum::name).toList().contains(series.engine()))throw invalid("画像来源不在原检测白名单内");
var start=time(selection.windowStart());var end=time(selection.windowEnd());var ids=new HashSet<Long>();var times=new HashSet<LocalDateTime>();
for(var point:series.points())if(point==null||!selection.snapshotIds().contains(Long.toString(point.snapshotId()))||!ids.add(point.snapshotId())||point.rowCount()<0||point.observedAt()==null||point.startedAt()==null||point.startedAt().isAfter(point.observedAt())||point.observedAt().isBefore(start)||point.observedAt().isAfter(end)||!times.add(point.observedAt())||point.statisticsSha()==null||!point.statisticsSha().matches("[0-9a-f]{64}"))throw invalid("历史观察必须同源、独立、位于选定范围且具有统计证明");
var sorted=series.points().stream().sorted(Comparator.comparing(ProfileSeriesOwner.Point::observedAt)).toList();var historical=sorted.subList(0,sorted.size()-1);var last=sorted.getLast();
var baseline=policy.baseline(historical.stream().map(p->BigDecimal.valueOf(p.rowCount())).toList(),config.minimumSamples(),config.deviationMultiplier());
if(baseline.lower()==null||baseline.upper()==null||baseline.lower().precision()>24||baseline.upper().precision()>24)throw invalid("真实观察不足或阈值超出原表单精度");
var baselineView=new AnomalyDetectionApi.BaselineView(0,config.detectionId(),baseline.algorithm(),baseline.version(),baseline.sampleCount(),baseline.lower(),baseline.upper(),baseline.fallbackReason(),last.observedAt());
var observation=new AnomalyDetectionApi.ObservationView(last.snapshotId(),config.detectionId(),AnomalyDetectionApi.SourceType.valueOf(series.engine()),"profile:"+last.snapshotId(),last.observedAt(),last.statisticsSha(),true,null,null,last.rowCount(),null,null,null,null,null,null,null,null,null,null,last.observedAt());
var evaluation=policy.evaluate(config,observation,config.thresholdStrategy()==AnomalyDetectionApi.ThresholdStrategy.BASELINE?baselineView:null,LocalDateTime.now());
var points=new ArrayList<Point>();for(var point:sorted)points.add(new Point("P"+(points.size()+1),point.observedAt().toString(),Long.toString(point.rowCount())));
var bounds=config.thresholdStrategy()==AnomalyDetectionApi.ThresholdStrategy.FIXED?new BigDecimal[]{config.fixedLower(),config.fixedUpper()}:new BigDecimal[]{baseline.lower(),baseline.upper()};
return new Context(selection,policy.inputSummaryHash(List.of(selection,config,series)),series.sourceLabel(),"表行数独立聚合观察;时间是采样完成时间,不是业务发生窗口。最后一个点单独核对,之前的点计算中位数/MAD候选。本次只读计算不覆盖原检测结果。",List.copyOf(points),new Evaluation(evaluation.verdict().name(),evaluation.reasonCode(),evaluation.algorithm(),evaluation.algorithmVersion(),text(bounds[0]),text(bounds[1])),List.of(new ThresholdOption("ROBUST_BASELINE",text(baseline.lower()),text(baseline.upper()),baseline.sampleCount(),baseline.fallbackReason())));
}
private static String text(BigDecimal value){return value==null?null:value.toPlainString();}
static long id(String value){try{if(value==null||!value.matches("[1-9][0-9]{0,18}"))throw invalid("历史对象ID无效");return Long.parseLong(value);}catch(NumberFormatException e){throw invalid("历史对象ID无效");}}
private static LocalDateTime time(String value){try{if(value==null||!value.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"))throw invalid("观察时间格式无效");return LocalDateTime.parse(value);}catch(java.time.format.DateTimeParseException e){throw invalid("观察时间格式无效");}}
private static AnomalyDetectionDomainException invalid(String text){return AnomalyDetectionDomainException.validation(text);}
}
@@ -0,0 +1,16 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory.*;
import cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service @RequiredArgsConstructor
class AnomalySeriesService {
private final AnomalyDetectionJdbcRepository repository;private final AnomalyDetectionActorProvider actors;private final AnomalySeriesAuthority authority;private final ProfileSeriesOwner profiles;private final AnomalyDetectionPolicy policy;
List<Choice> choices(long id,long version){var actor=actors.current();authority.require(actor,false);var config=repository.detection(id,actor);if(config.version()!=version||config.detectionType()!=AnomalyDetectionApi.DetectionType.VOLUME)throw AnomalyDetectionDomainException.conflict("请选择当前表行数检测");var result=profiles.choices();if(!config.equals(repository.detection(id,actor)))throw AnomalyDetectionDomainException.conflict("检测配置已变化");authority.require(actor,false);return result;}
record Verified(AnomalyDetectionApi.DetectionView config,ProfileSeriesOwner.Series series,Context context) { }
Context current(Selection raw,boolean ai){return verified(raw,ai).context();}
Verified verified(Selection raw,boolean ai){var selection=AnomalySeriesPolicy.normalize(raw);var actor=actors.current();authority.require(actor,ai);var id=AnomalySeriesPolicy.id(selection.detectionId());var config=repository.detection(id,actor);AnomalySeriesPolicy.config(config,selection);
var series=profiles.current(selection.snapshotIds().stream().map(AnomalySeriesPolicy::id).toList(),config.targetLogicalId());var value=AnomalySeriesPolicy.calculate(selection,config,series,policy);
if(!config.equals(repository.detection(id,actor)))throw AnomalyDetectionDomainException.conflict("检测配置已变化");authority.require(actor,ai);return new Verified(config,series,value);}
}
@@ -0,0 +1,135 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
import cn.aixunkeji.datagov.governance.api.anomalydetection.AnomalySeriesDirectory.Selection;
import cn.aixunkeji.datagov.governance.dataprofile.ProfileSeriesOwner;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import tools.jackson.databind.ObjectMapper;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import static cn.aixunkeji.datagov.governance.anomalydetection.AnomalyDetectionApi.*;
/** Evidence can only be produced by rereading the original, physically bound profile runs. */
@Service @RequiredArgsConstructor
public class AnomalySourceEvidence {
static final String PATH = "/api/governance/v1/anomaly-detections/assist/evaluations";
public record Result(String resultId,String detectionId,long configVersion,String targetLogicalId,String targetFqn,
String name,String configSha,String thresholdSha,String ownerSha,String verdict,long observedValue,
LocalDateTime observedAt,LocalDateTime evaluatedAt,String evidenceSha,LocalDateTime samplingStartedAt) { }
record Save(Selection selection,String fingerprint) { }
record Stored(Selection selection,String contextSha,String configSha,String thresholdSha,String ownerSha,LocalDateTime observedAt) { }
private final AnomalyDetectionJdbcRepository repository;
private final AnomalyDetectionActorProvider actors;
private final AnomalySeriesAuthority authority;
private final AnomalySeriesService series;
private final ProfileSeriesOwner profiles;
private final AnomalyDetectionPolicy policy;
private final JdbcTemplate jdbc;
private final ObjectMapper json;
private final TransactionTemplate transactions;
Result save(String rawKey,Save raw) {
if(raw==null||raw.fingerprint()==null||!raw.fingerprint().matches("[0-9a-f]{64}"))throw invalid();
var selection=AnomalySeriesPolicy.normalize(raw.selection());var actor=actors.current();authority.requireEvaluation(actor);
String key=policy.idempotencyKey(rawKey),hash=policy.requestHash(new Save(selection,raw.fingerprint()));
Long id=transactions.execute(tx->{
var ticket=repository.beginRequest(actor,"POST",PATH,key,hash);
if(ticket.objectId()!=null){if(ticket.objectType()!=AnomalyDetectionJdbcRepository.ObjectType.RESULT)throw invalid();return ticket.objectId();}
var config=repository.lockIssueDetection(AnomalySeriesPolicy.id(selection.detectionId()),actor);
var verified=series.verified(selection,false);
if(!config.equals(verified.config())||config.status()!=Status.ENABLED||!raw.fingerprint().equals(verified.context().fingerprint()))throw invalid();
var last=last(verified);var evaluation=evaluation(verified);
var observationCommand=new ObservationCommand(SourceType.valueOf(verified.series().engine()),"profile:"+last.snapshotId(),
last.observedAt(),verified.context().fingerprint(),true,null,null,last.rowCount(),null,null,null,null,null,null,null,null,null,null,config.version());
long observationId=repository.createObservation(actor,config.detectionId(),observationCommand,ticket.requestId());
var observation=repository.observationForDetection(observationId,config.detectionId());
requireObservation(observation,verified);
long resultId=repository.createResult(actor,config,observation,evaluation,verified.context().fingerprint(),ticket.requestId());
requireResult(repository.result(resultId),observation,verified);
var stored=new Stored(selection,verified.context().fingerprint(),configHash(verified),thresholdHash(verified),verified.series().ownerSha(),last.observedAt());
var frozen=result(repository.result(resultId),stored,verified);
jdbc.update("""
INSERT /*+ IGNORE_ROW_ON_DUPKEY_INDEX(dq_anomaly_source_evidence) */ INTO dq_anomaly_source_evidence(result_id,detection_id,organization_id,department_id,
selection_json,frozen_result_json,context_sha256,config_sha256,threshold_sha256,owner_sha256,observed_at,create_dept,create_by,update_by)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""",resultId,config.detectionId(),actor.organizationId(),actor.departmentId(),json.writeValueAsString(selection),
json.writeValueAsString(frozen),stored.contextSha(),stored.configSha(),stored.thresholdSha(),stored.ownerSha(),stored.observedAt(),actor.departmentId(),actor.actorId(),actor.actorId());
if(!verified.equals(series.verified(selection,false)))throw invalid();authority.requireEvaluation(actor);
repository.completeRequest(actor,"POST",PATH,key,AnomalyDetectionJdbcRepository.ObjectType.RESULT,resultId);
return resultId;
});
if(id==null)throw new IllegalStateException("异常评估结果尚未确认");
try{return request(key);}catch(RuntimeException readback){throw new IllegalStateException("评估已提交,请读取原请求",readback);}
}
Result request(String rawKey) {
var actor=actors.current();authority.requireEvaluation(actor);String key=policy.idempotencyKey(rawKey);
var ids=jdbc.query("""
SELECT response_object_id FROM dq_anomaly_request WHERE actor_id=? AND organization_id=? AND department_id=?
AND request_method='POST' AND request_path=? AND idempotency_key=? AND request_status='COMPLETED'
AND response_object_type='RESULT' AND del_flag='0'
""",(r,n)->r.getLong(1),actor.actorId(),actor.organizationId(),actor.departmentId(),PATH,key);
if(ids.isEmpty())return null;
// Reading an existing receipt never starts another evaluation.
var found=jdbc.query("SELECT selection_json,frozen_result_json FROM dq_anomaly_source_evidence WHERE result_id=? AND organization_id=? AND department_id=?",
(r,n)->new Receipt(json.readValue(r.getString(1),Selection.class),json.readValue(r.getString(2),Result.class)),ids.getFirst(),actor.organizationId(),actor.departmentId())
.stream().findFirst().orElseThrow(AnomalySourceEvidence::invalid);
var current=profiles.current(found.selection().snapshotIds().stream().map(AnomalySeriesPolicy::id).toList(),found.result().targetLogicalId());
var last=current.points().stream().max(Comparator.comparing(ProfileSeriesOwner.Point::observedAt)).orElseThrow(AnomalySourceEvidence::invalid);
if(!Objects.equals(current.ownerSha(),found.result().ownerSha())||last.rowCount()!=found.result().observedValue()
||!last.observedAt().equals(found.result().observedAt())||!Objects.equals(last.startedAt(),found.result().samplingStartedAt()))throw invalid();
authority.requireEvaluation(actor);return found.result();
}
private record Receipt(Selection selection,Result result) { }
public Result current(long resultId) {
var actor=actors.current();authority.require(actor,false);
var result=repository.result(resultId);var config=repository.detection(result.detectionId(),actor);
var stored=jdbc.query("""
SELECT selection_json,context_sha256,config_sha256,threshold_sha256,owner_sha256,observed_at
FROM dq_anomaly_source_evidence WHERE result_id=? AND detection_id=? AND organization_id=? AND department_id=?
""",(r,n)->new Stored(json.readValue(r.getString(1),Selection.class),r.getString(2),r.getString(3),r.getString(4),r.getString(5),r.getObject(6,LocalDateTime.class)),
resultId,config.detectionId(),actor.organizationId(),actor.departmentId()).stream().findFirst().orElseThrow(AnomalySourceEvidence::invalid);
var verified=series.verified(stored.selection(),false);var observation=repository.observationForDetection(result.observationId(),config.detectionId());
if(!config.equals(verified.config())||!stored.contextSha().equals(verified.context().fingerprint())
||!stored.configSha().equals(configHash(verified))||!stored.thresholdSha().equals(thresholdHash(verified))
||!stored.ownerSha().equals(verified.series().ownerSha())||!stored.observedAt().equals(last(verified).observedAt()))throw invalid();
requireObservation(observation,verified);requireResult(result,observation,verified);authority.require(actor,false);
return result(result,stored,verified);
}
public Result remediationSource(long resultId) {
try{return current(resultId);}
catch(AnomalyDetectionDomainException rejected){throw new cn.aixunkeji.datagov.governance.qualityremediation.QualityRemediationSourceException(rejected.code(),rejected.status(),rejected.getMessage());}
catch(ProfileSeriesOwner.SourceException rejected){throw new cn.aixunkeji.datagov.governance.qualityremediation.QualityRemediationSourceException(rejected.code(),rejected.status(),rejected.getMessage());}
}
private Result result(ResultView result,Stored stored,AnomalySeriesService.Verified verified){var config=verified.config();String sha=policy.inputSummaryHash(List.of(result,stored));
return new Result(Long.toString(result.resultId()),Long.toString(config.detectionId()),config.version(),config.targetLogicalId(),config.targetFqn(),
config.detectionName(),stored.configSha(),stored.thresholdSha(),stored.ownerSha(),result.verdict().name(),last(verified).rowCount(),stored.observedAt(),result.evaluatedAt(),sha,last(verified).startedAt());}
public List<Result> results(long detectionId) {
var actor=actors.current();authority.require(actor,false);repository.detection(detectionId,actor);
var ids=jdbc.query("SELECT result_id FROM dq_anomaly_source_evidence WHERE detection_id=? AND organization_id=? AND department_id=? ORDER BY observed_at DESC,result_id DESC LIMIT 100",
(r,n)->r.getLong(1),detectionId,actor.organizationId(),actor.departmentId());
var values=new ArrayList<Result>();for(long id:ids)try{values.add(current(id));}catch(AnomalyDetectionDomainException|ProfileSeriesOwner.SourceException stale){/* Ineligible historic sources are not selectable. */}
authority.require(actor,false);return List.copyOf(values);
}
private static ProfileSeriesOwner.Point last(AnomalySeriesService.Verified verified){return verified.series().points().stream().max(Comparator.comparing(ProfileSeriesOwner.Point::observedAt)).orElseThrow(AnomalySourceEvidence::invalid);}
private String configHash(AnomalySeriesService.Verified v){return policy.inputSummaryHash(v.config());}
private String thresholdHash(AnomalySeriesService.Verified v){var e=v.context().evaluation();return policy.inputSummaryHash(Arrays.asList(e.algorithm(),e.algorithmVersion(),e.lower(),e.upper()));}
private static AnomalyDetectionPolicy.Evaluation evaluation(AnomalySeriesService.Verified v){var e=v.context().evaluation();var option=v.context().thresholdOptions().getFirst();
return new AnomalyDetectionPolicy.Evaluation(Verdict.valueOf(e.verdict()),e.reasonCode(),"同一物理表真实画像序列评估",e.algorithm(),e.algorithmVersion(),
v.series().points().size()-1,decimal(e.lower()),decimal(e.upper()),v.config().thresholdStrategy()==ThresholdStrategy.BASELINE?option.fallbackReason():null);}
private static BigDecimal decimal(String value){return value==null?null:new BigDecimal(value);}
static void requireObservation(ObservationView o,AnomalySeriesService.Verified v){var p=last(v);
if(!o.reliable()||o.detectionId()!=v.config().detectionId()||!Objects.equals(o.payloadSha(),v.context().fingerprint())
||!Objects.equals(o.observedAt(),p.observedAt())||!Objects.equals(o.rowCount(),p.rowCount())
||!Objects.equals(o.externalRef(),"profile:"+p.snapshotId())||!o.sourceType().name().equals(v.series().engine()))throw invalid();}
static void requireResult(ResultView r,ObservationView o,AnomalySeriesService.Verified v){var e=evaluation(v);
if(r.detectionId()!=v.config().detectionId()||r.configVersion()!=v.config().version()||r.observationId()!=o.observationId()
||!Objects.equals(r.observationSha(),o.payloadSha())||!Objects.equals(r.inputSummarySha(),v.context().fingerprint())
||r.verdict()!=e.verdict()||!Objects.equals(r.reasonCode(),e.reasonCode())||!Objects.equals(r.algorithm(),e.algorithm())
||!Objects.equals(r.algorithmVersion(),e.algorithmVersion())||!Objects.equals(r.sampleCount(),e.sampleCount())||!Objects.equals(r.fallbackReason(),e.fallbackReason())||!same(r.lowerBound(),e.lower())||!same(r.upperBound(),e.upper())
||r.evaluatedAt()==null||r.evaluatedAt().isBefore(o.observedAt())||r.evaluatedAt().isAfter(LocalDateTime.now().plusMinutes(5)))throw invalid();}
private static boolean same(BigDecimal a,BigDecimal b){return a==null?b==null:b!=null&&a.compareTo(b)==0;}
static AnomalyDetectionDomainException invalid(){return AnomalyDetectionDomainException.conflict("缺少同一目标与配置的真实画像序列证明,请重新核对并登记评估");}
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.governance.anomalydetection;
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 P57OwnerContext implements PageAssistContextReader {
private final AnomalyDetectionService service;
@Override public String pageId(){return "P57";}
@Override public Snapshot read(Request r){
qualifiers(r);var v=service.detail(numeric(r));
return snapshot(r,v.version(),"status",v.status(),"version",v.version(),"thresholdStrategy",v.thresholdStrategy(),"updateTime",v.updateTime());
}
}
@@ -0,0 +1,71 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextDirectory.*;
import java.util.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import static cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceApi.*;
import static cn.aixunkeji.datagov.integration.api.aiassistant.PageAssistContextReader.*;
/** Explains the original registered-plan check, never certifies its external source. */
@Component @RequiredArgsConstructor
final class ArchitectureCheckEvidence {
private final ArchitectureGovernancePolicy policy;
static long id(String value) {
try { if(value==null||!value.matches("[1-9][0-9]{0,18}"))throw denied();return Long.parseLong(value); }
catch(NumberFormatException e){throw denied();}
}
Snapshot project(Request request,ProposalView proposal,CheckRunView check,RuleSnapshotView rules,long itemId) {
if(proposal==null||check==null||rules==null||proposal.proposalId()!=numeric(request)
||check.proposalId()!=proposal.proposalId()||rules.proposalId()!=proposal.proposalId()
||check.checkRunId()<=0||check.ruleSnapshotId()!=rules.ruleSnapshotId()||rules.ruleSnapshotId()<=0
||check.items()==null||check.items().isEmpty()||check.items().size()>100||rules.rules()==null
||check.items().size()!=rules.rules().size()||check.createTime()==null)throw denied();
var input=new CreateProposalCommand(proposal.proposalCode(),proposal.proposalName(),proposal.proposalType(),
proposal.modelLogicalId(),proposal.modelDisplayName(),proposal.impactStatement(),proposal.sourceRef(),proposal.sourceVersion(),proposal.payloadSha256(),proposal.plan());
var normalized=policy.normalize(input);
var normalizedRules=policy.normalize(new RuleSnapshotCommand(rules.sourceRef(),rules.sourceVersion(),rules.payloadSha256(),rules.rules(),proposal.version()));
if(!Objects.equals(normalized.payloadSha256(),check.inputSha256())||!Objects.equals(proposal.payloadSha256(),check.inputSha256())
||!Objects.equals(policy.rulesSha(normalizedRules.rules()),rules.rulesSha256())||!Objects.equals(rules.rulesSha256(),check.rulesSha256()))throw denied();
// Reading an explanation must not run a user-supplied regex again.
// NAMING uses its already completed immutable result; fixed comparisons are rechecked.
var expected=normalizedRules.rules().stream().map(rule->{
if(rule.ruleType()!=RuleType.NAMING)return policy.evaluate(normalized.plan(),List.of(rule)).getFirst();
var originals=check.items().stream().filter(i->i!=null&&Objects.equals(i.ruleCode(),rule.ruleCode())).toList();
if(originals.size()!=1||originals.getFirst().status()==null||originals.getFirst().status()==CheckStatus.UNKNOWN)throw denied();
return new ArchitectureGovernancePolicy.EvaluatedRule(rule,originals.getFirst().status(),"对象名称按规则快照匹配");
}).toList();
if(policy.overall(expected)!=check.overallStatus())throw denied();
var byCode=new HashMap<String,ArchitectureGovernancePolicy.EvaluatedRule>();
for(var result:expected)if(byCode.put(result.rule().ruleCode(),result)!=null)throw denied();
var ids=new HashSet<Long>();var codes=new HashSet<String>();CheckItemView selected=null;
for(var item:check.items()) {
if(item==null||item.checkItemId()<=0||!ids.add(item.checkItemId())||!codes.add(item.ruleCode())||item.checkRunId()!=check.checkRunId())throw denied();
var result=byCode.get(item.ruleCode());
if(result==null||result.rule().ruleType()!=item.ruleType()||result.status()!=item.status()
||!Objects.equals(result.rule().expectedValue(),item.expectedValue())||!Objects.equals(result.reason(),item.reason()))throw denied();
if(item.checkItemId()==itemId)selected=item;
}
if(selected==null)throw denied();
var rule=byCode.get(selected.ruleCode()).rule();
var actual=switch(rule.ruleType()) {case NAMING->proposal.plan().objectName();case LAYERING->proposal.plan().layerCode();case DATA_TYPE->proposal.plan().dataType();default->null;};
var list=switch(rule.ruleType()) {case COMMON_FIELD->proposal.plan().commonFields();case SECURITY->proposal.plan().securityTags();default->null;};
String missing=null;
if(list!=null&&!list.isEmpty()) {
var present=new HashSet<String>();list.forEach(v->present.add(v.toUpperCase(Locale.ROOT)));
missing=String.join(",",Arrays.stream(rule.expectedValue().split(",")).map(String::trim).filter(v->!present.contains(v.toUpperCase(Locale.ROOT))).toList());
if(missing.isEmpty())missing="无";
}
var values=new TreeMap<String,Object>(facts("status",proposal.status(),"version",proposal.version(),"proposalType",proposal.proposalType(),"updateTime",proposal.updateTime(),
"selectionState","CHECK_ITEM","sourceVerification","NOT_VERIFIED","checkRunId",Long.toString(check.checkRunId()),"checkItemId",Long.toString(itemId),
"ruleSnapshotId",Long.toString(rules.ruleSnapshotId()),"checkedAt",check.createTime(),"overallStatus",check.overallStatus(),
"ruleCode",rule.ruleCode(),"ruleType",rule.ruleType(),"required",rule.required(),"checkStatus",selected.status(),"checkReason",selected.reason(),
"declaredValue",actual,"declaredListCount",list==null?null:list.size(),
"passCount",check.items().stream().filter(i->i.status()==CheckStatus.PASS).count(),"failCount",check.items().stream().filter(i->i.status()==CheckStatus.FAIL).count(),"unknownCount",check.items().stream().filter(i->i.status()==CheckStatus.UNKNOWN).count()));
values.put("expectedValue",text(selected.expectedValue()));values.put("missingExpectedValues",text(missing));
return new Snapshot(request.pageId(),request.reference(),proposal.version()+":"+check.checkRunId()+":"+itemId,Collections.unmodifiableMap(values));
}
private static String text(String value){if(value!=null&&(value.length()>1000||value.chars().anyMatch(c->Character.isISOControl(c)&&c!='\n'&&c!='\r'&&c!='\t')))throw denied();return value;}
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Component;
@Component
class ArchitectureGovernanceActorProvider {
Actor current() {
Long actorId = LoginHelper.getUserId();
Long departmentId = LoginHelper.getDeptId();
if (actorId == null || departmentId == null || actorId <= 0 || departmentId <= 0) {
throw ArchitectureGovernanceDomainException.forbidden();
}
return new Actor(actorId, departmentId, departmentId);
}
record Actor(long actorId, long organizationId, long departmentId) { }
}
@@ -0,0 +1,56 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import java.time.LocalDateTime;
import java.util.List;
final class ArchitectureGovernanceApi {
private ArchitectureGovernanceApi() { }
enum ProposalType { NEW, CHANGE }
enum ProposalStatus { OPEN, IN_REVIEW, CONCLUDED }
enum RuleType { NAMING, LAYERING, DATA_TYPE, COMMON_FIELD, SECURITY }
enum CheckStatus { PASS, FAIL, UNKNOWN }
enum ConclusionType { APPROVED, CONDITIONAL, REJECTED }
enum TimelineType { CREATED, RULES_SNAPSHOTTED, CHECKED, REVIEW_OPENED, COMMENTED, ATTACHED, CONCLUDED }
record StructuredPlan(String objectName, String layerCode, String dataType,
List<String> commonFields, List<String> securityTags) { }
record CreateProposalCommand(String proposalCode, String proposalName, ProposalType proposalType,
String modelLogicalId, String modelDisplayName,
String impactStatement, String sourceRef,
String sourceVersion, String payloadSha256, StructuredPlan plan) { }
record RuleDefinition(String ruleCode, RuleType ruleType, String expectedValue, boolean required,
String rationale) { }
record RuleSnapshotCommand(String sourceRef, String sourceVersion, String payloadSha256,
List<RuleDefinition> rules, Long version) { }
record CheckCommand(long ruleSnapshotId, String inputSha256, Long version) { }
record ReviewCommand(String reviewTitle, String reviewBasis, Long version) { }
record CommentCommand(String content, Long version) { }
record ConclusionCommand(ConclusionType conclusion, long checkRunId, String basis, Long version) { }
record AttachmentCommand(String fileRef, String fileName, long fileSize, String fileSha256, Long version) { }
record ProposalView(long proposalId, String proposalCode, String proposalName, ProposalType proposalType,
String modelLogicalId, String modelDisplayName,
String impactStatement, String sourceRef,
String sourceVersion, String payloadSha256, StructuredPlan plan,
ProposalStatus status, long organizationId, long departmentId, long version,
LocalDateTime createTime, LocalDateTime updateTime) { }
record RuleSnapshotView(long ruleSnapshotId, long proposalId, String sourceRef, String sourceVersion,
String payloadSha256, String rulesSha256, List<RuleDefinition> rules,
LocalDateTime createTime) { }
record CheckItemView(long checkItemId, long checkRunId, String ruleCode, RuleType ruleType,
CheckStatus status, String reason, String expectedValue) { }
record CheckRunView(long checkRunId, long proposalId, long ruleSnapshotId, String inputSha256,
String rulesSha256, CheckStatus overallStatus, List<CheckItemView> items,
LocalDateTime createTime) { }
record ReviewView(long reviewId, long proposalId, String reviewTitle, String reviewBasis,
long openedBy, LocalDateTime createTime) { }
record CommentView(long commentId, long reviewId, String content, long actorId, LocalDateTime createTime) { }
record ConclusionView(long conclusionId, long reviewId, ConclusionType conclusion, long checkRunId,
String basis, long actorId, LocalDateTime createTime) { }
record AttachmentView(long attachmentId, long reviewId, String fileRef, String fileName, long fileSize,
String fileSha256, long actorId, LocalDateTime createTime) { }
record TimelineView(long timelineId, long proposalId, TimelineType eventType, String eventSummary,
String requestId, long actorId, LocalDateTime createTime) { }
record WriteView<T>(String requestId, T result) { }
}
@@ -0,0 +1,159 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
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.governance.architecturegovernance.ArchitectureGovernanceApi.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.aixunkeji.datagov.governance.modeldesign.ModelDesignSourceFacade;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/governance/v1/architecture-governance")
public class ArchitectureGovernanceController {
private final ArchitectureGovernanceService service;
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping
public R<PageResult<ProposalView>> page(@RequestParam(required = false) String keyword,
@RequestParam(required = false) ProposalStatus status,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.page(keyword, status, pageNum, pageSize));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}")
public R<ProposalView> detail(@PathVariable long proposalId) { return R.ok(service.detail(proposalId)); }
@SaCheckPermission(value = {"aixun:governance:architecture-governance:create",
"aixun:governance:model-design:view"}, mode = SaMode.AND)
@GetMapping("/model-sources")
public R<PageResult<ModelDesignSourceFacade.Source>> modelSources(@RequestParam(required = false) String keyword,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.modelSources(keyword, pageNum, pageSize));
}
@Log(title = "架构方案登记", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:create")
@PostMapping
public R<WriteView<ProposalView>> create(@RequestHeader("Idempotency-Key") String key,
@RequestBody CreateProposalCommand command) {
return R.ok(service.create(key, command));
}
@Log(title = "架构规则快照", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:check")
@PostMapping("/{proposalId}/rule-snapshots")
public R<WriteView<RuleSnapshotView>> snapshot(@PathVariable long proposalId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody RuleSnapshotCommand command) {
return R.ok(service.snapshot(proposalId, key, command));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/rule-snapshots")
public R<PageResult<RuleSnapshotView>> snapshots(@PathVariable long proposalId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.snapshots(proposalId, pageNum, pageSize));
}
@Log(title = "架构规范检查", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:check")
@PostMapping("/{proposalId}/checks")
public R<WriteView<CheckRunView>> check(@PathVariable long proposalId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody CheckCommand command) {
return R.ok(service.check(proposalId, key, command));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/checks")
public R<PageResult<CheckRunView>> checks(@PathVariable long proposalId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.checks(proposalId, pageNum, pageSize));
}
@Log(title = "架构评审开启", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:review")
@PostMapping("/{proposalId}/reviews")
public R<WriteView<ReviewView>> review(@PathVariable long proposalId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody ReviewCommand command) {
return R.ok(service.review(proposalId, key, command));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/reviews/{reviewId}")
public R<ReviewView> review(@PathVariable long proposalId, @PathVariable long reviewId) {
return R.ok(service.review(proposalId, reviewId));
}
@Log(title = "架构评审意见", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:review")
@PostMapping("/{proposalId}/reviews/{reviewId}/comments")
public R<WriteView<CommentView>> comment(@PathVariable long proposalId, @PathVariable long reviewId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody CommentCommand command) {
return R.ok(service.comment(proposalId, reviewId, key, command));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/reviews/{reviewId}/comments")
public R<PageResult<CommentView>> comments(@PathVariable long proposalId, @PathVariable long reviewId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.comments(proposalId, reviewId, pageNum, pageSize));
}
@Log(title = "架构评审结论", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:conclude")
@PostMapping("/{proposalId}/reviews/{reviewId}/conclusion")
public R<WriteView<ConclusionView>> conclude(@PathVariable long proposalId, @PathVariable long reviewId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody ConclusionCommand command) {
return R.ok(service.conclude(proposalId, reviewId, key, command));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/reviews/{reviewId}/conclusion")
public R<ConclusionView> conclusion(@PathVariable long proposalId, @PathVariable long reviewId) {
return R.ok(service.conclusion(proposalId, reviewId));
}
@Log(title = "架构评审附件引用", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:architecture-governance:attach")
@PostMapping("/{proposalId}/reviews/{reviewId}/attachments")
public R<WriteView<AttachmentView>> attach(@PathVariable long proposalId, @PathVariable long reviewId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody AttachmentCommand command) {
return R.ok(service.attach(proposalId, reviewId, key, command));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/reviews/{reviewId}/attachments")
public R<PageResult<AttachmentView>> attachments(@PathVariable long proposalId, @PathVariable long reviewId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.attachments(proposalId, reviewId, pageNum, pageSize));
}
@SaCheckPermission("aixun:governance:architecture-governance:view")
@GetMapping("/{proposalId}/timeline")
public R<PageResult<TimelineView>> timeline(@PathVariable long proposalId,
@RequestParam(required = false) Integer pageNum,
@RequestParam(required = false) Integer pageSize) {
return R.ok(service.timeline(proposalId, pageNum, pageSize));
}
@SaCheckPermission("aixun:governance:architecture-governance:status")
@GetMapping("/{proposalId}/status")
public R<ProposalStatus> status(@PathVariable long proposalId) { return R.ok(service.detail(proposalId).status()); }
}
@@ -0,0 +1,36 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import org.springframework.http.HttpStatus;
final class ArchitectureGovernanceDomainException extends RuntimeException {
static final int VALIDATION_CODE = 136401;
static final int FORBIDDEN_CODE = 136403;
static final int NOT_FOUND_CODE = 136404;
static final int CONFLICT_CODE = 136409;
private final int code;
private final HttpStatus status;
private ArchitectureGovernanceDomainException(int code, HttpStatus status, String message) {
super(message);
this.code = code;
this.status = status;
}
static ArchitectureGovernanceDomainException validation(String message) {
return new ArchitectureGovernanceDomainException(VALIDATION_CODE, HttpStatus.BAD_REQUEST, message);
}
static ArchitectureGovernanceDomainException forbidden() {
return new ArchitectureGovernanceDomainException(FORBIDDEN_CODE, HttpStatus.FORBIDDEN, "无权访问架构治理资源");
}
static ArchitectureGovernanceDomainException notFound() {
return new ArchitectureGovernanceDomainException(NOT_FOUND_CODE, HttpStatus.NOT_FOUND, "架构治理资源不存在");
}
static ArchitectureGovernanceDomainException conflict(String message) {
return new ArchitectureGovernanceDomainException(CONFLICT_CODE, HttpStatus.CONFLICT, message);
}
static ArchitectureGovernanceDomainException unavailable() {
return new ArchitectureGovernanceDomainException(136503, HttpStatus.SERVICE_UNAVAILABLE, "模型设计来源暂时不可核验");
}
int code() { return code; }
HttpStatus status() { return status; }
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
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 = ArchitectureGovernanceController.class)
class ArchitectureGovernanceExceptionHandler {
@ExceptionHandler(ArchitectureGovernanceDomainException.class)
ResponseEntity<R<Void>> handle(ArchitectureGovernanceDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,351 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceActorProvider.Actor;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceApi.*;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernancePolicy.EvaluatedRule;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
@Repository
@RequiredArgsConstructor
class ArchitectureGovernanceJdbcRepository {
private static final String PROPOSAL_SELECT = """
SELECT proposal_id,proposal_code,proposal_name,proposal_type,model_logical_id,model_display_name,
impact_statement,source_ref,source_version,payload_sha256,
plan_json,proposal_status,organization_id,department_id,version,create_time,update_time
FROM da_architecture_proposal
""";
private static final String SNAPSHOT_SELECT = """
SELECT rule_snapshot_id,proposal_id,source_ref,source_version,payload_sha256,rules_sha256,rules_json,create_time
FROM da_architecture_rule_snapshot
""";
private static final String CHECK_SELECT = """
SELECT check_run_id,proposal_id,rule_snapshot_id,input_sha256,rules_sha256,overall_status,create_time
FROM da_architecture_check_run
""";
private final JdbcTemplate jdbc;
private final ArchitectureGovernancePolicy policy;
ProposalPage page(Actor actor, String keyword, ProposalStatus status, int pageNum, int pageSize) {
String filter = " WHERE organization_id=? AND department_id=? AND del_flag='0'"
+ (keyword == null ? "" : " AND (proposal_code LIKE ? OR proposal_name LIKE ?)")
+ (status == null ? "" : " AND proposal_status=?");
List<Object> args = new java.util.ArrayList<>(List.of(actor.organizationId(), actor.departmentId()));
if (keyword != null) { args.add("%" + keyword + "%"); args.add("%" + keyword + "%"); }
if (status != null) args.add(status.name());
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM da_architecture_proposal" + filter, Long.class, args.toArray());
args.add(pageSize); args.add((pageNum - 1) * pageSize);
List<ProposalView> rows = jdbc.query(PROPOSAL_SELECT + filter + " ORDER BY update_time DESC,proposal_id DESC LIMIT ? OFFSET ?",
this::proposalView, args.toArray());
return new ProposalPage(rows, total == null ? 0 : total);
}
ProposalView detail(long proposalId, Actor actor) {
return one(PROPOSAL_SELECT + " WHERE proposal_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
this::proposalView, proposalId, actor.organizationId(), actor.departmentId());
}
long create(Actor actor, CreateProposalCommand value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO da_architecture_proposal(proposal_id,proposal_code,proposal_name,proposal_type,
model_logical_id,model_display_name,project_logical_id,project_display_name,impact_statement,
source_ref,source_version,payload_sha256,plan_json,proposal_status,organization_id,department_id,
create_dept,create_by,create_time,update_by,update_time,del_flag,version)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,'OPEN',?,?,?,?,NOW(),?,NOW(),'0',0)
""", id, value.proposalCode(), value.proposalName(), value.proposalType().name(), value.modelLogicalId(),
value.modelDisplayName(), null, null, value.impactStatement(),
value.sourceRef(), value.sourceVersion(), value.payloadSha256(), policy.writeJson(value.plan()),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) { throw ArchitectureGovernanceDomainException.conflict("同作用域方案编码已存在"); }
timeline(actor, id, TimelineType.CREATED, "架构方案及来源SHA已登记", requestId);
return id;
}
long snapshot(Actor actor, ProposalView proposal, RuleSnapshotCommand value, String rulesSha, String requestId) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO da_architecture_rule_snapshot(rule_snapshot_id,proposal_id,source_ref,source_version,
payload_sha256,rules_sha256,rules_json,organization_id,department_id,create_dept,create_by,create_time)
VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW())
""", id, proposal.proposalId(), value.sourceRef(), value.sourceVersion(), value.payloadSha256(), rulesSha,
policy.writeJson(value.rules()), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
} catch (DuplicateKeyException exception) {
Long existing = jdbc.queryForObject("SELECT rule_snapshot_id FROM da_architecture_rule_snapshot WHERE proposal_id=? AND rules_sha256=?",
Long.class, proposal.proposalId(), rulesSha);
if (existing != null) return existing;
throw exception;
}
bumpVersion(actor, proposal.proposalId(), value.version());
timeline(actor, proposal.proposalId(), TimelineType.RULES_SNAPSHOTTED, "五类规则不可变快照已登记", requestId);
return id;
}
RuleSnapshotView snapshot(long snapshotId, long proposalId, Actor actor) {
return one(SNAPSHOT_SELECT + " WHERE rule_snapshot_id=? AND proposal_id=? AND organization_id=? AND department_id=?",
this::snapshotView, snapshotId, proposalId, actor.organizationId(), actor.departmentId());
}
SnapshotPage snapshots(long proposalId, Actor actor, int pageNum, int pageSize) {
requireProposal(proposalId, actor);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM da_architecture_rule_snapshot WHERE proposal_id=? AND organization_id=? AND department_id=?",
Long.class, proposalId, actor.organizationId(), actor.departmentId());
List<RuleSnapshotView> rows = jdbc.query(SNAPSHOT_SELECT + " WHERE proposal_id=? AND organization_id=? AND department_id=? ORDER BY create_time DESC,rule_snapshot_id DESC LIMIT ? OFFSET ?",
this::snapshotView, proposalId, actor.organizationId(), actor.departmentId(), pageSize, (pageNum - 1) * pageSize);
return new SnapshotPage(rows, total == null ? 0 : total);
}
long check(Actor actor, ProposalView proposal, RuleSnapshotView snapshot, String inputSha,
List<EvaluatedRule> values, CheckStatus overall, String requestId) {
Long existing = jdbc.query("SELECT check_run_id FROM da_architecture_check_run WHERE proposal_id=? AND input_sha256=? AND rules_sha256=?",
(rs, n) -> rs.getLong(1), proposal.proposalId(), inputSha, snapshot.rulesSha256()).stream().findFirst().orElse(null);
if (existing != null) return existing;
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("""
INSERT INTO da_architecture_check_run(check_run_id,proposal_id,rule_snapshot_id,input_sha256,
rules_sha256,overall_status,organization_id,department_id,create_dept,create_by,create_time)
VALUES(?,?,?,?,?,?,?,?,?,?,NOW())
""", id, proposal.proposalId(), snapshot.ruleSnapshotId(), inputSha, snapshot.rulesSha256(), overall.name(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
for (EvaluatedRule value : values) {
jdbc.update("""
INSERT INTO da_architecture_check_item(check_item_id,check_run_id,rule_code,rule_type,
check_status,reason,expected_value,organization_id,department_id,create_dept,create_by,create_time)
VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW())
""", IdGeneratorUtil.nextLongId(), id, value.rule().ruleCode(), value.rule().ruleType().name(),
value.status().name(), value.reason(), value.rule().expectedValue(), actor.organizationId(),
actor.departmentId(), actor.departmentId(), actor.actorId());
}
} catch (DuplicateKeyException exception) {
Long raced = jdbc.queryForObject("SELECT check_run_id FROM da_architecture_check_run WHERE proposal_id=? AND input_sha256=? AND rules_sha256=?",
Long.class, proposal.proposalId(), inputSha, snapshot.rulesSha256());
if (raced != null) return raced;
throw exception;
}
bumpVersion(actor, proposal.proposalId(), proposal.version());
timeline(actor, proposal.proposalId(), TimelineType.CHECKED, "确定性检查完成:" + overall.name(), requestId);
return id;
}
CheckRunView check(long checkRunId, long proposalId, Actor actor) {
CheckRow row = one(CHECK_SELECT + " WHERE check_run_id=? AND proposal_id=? AND organization_id=? AND department_id=?",
this::checkRow, checkRunId, proposalId, actor.organizationId(), actor.departmentId());
return checkView(row);
}
CheckPage checks(long proposalId, Actor actor, int pageNum, int pageSize) {
requireProposal(proposalId, actor);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM da_architecture_check_run WHERE proposal_id=? AND organization_id=? AND department_id=?",
Long.class, proposalId, actor.organizationId(), actor.departmentId());
List<CheckRunView> rows = jdbc.query(CHECK_SELECT + " WHERE proposal_id=? AND organization_id=? AND department_id=? ORDER BY create_time DESC,check_run_id DESC LIMIT ? OFFSET ?",
this::checkRow, proposalId, actor.organizationId(), actor.departmentId(), pageSize, (pageNum - 1) * pageSize)
.stream().map(this::checkView).toList();
return new CheckPage(rows, total == null ? 0 : total);
}
long review(Actor actor, ProposalView proposal, ReviewCommand value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
jdbc.update("""
INSERT INTO da_architecture_review(review_id,proposal_id,review_title,review_basis,opened_by,
organization_id,department_id,create_dept,create_by,create_time)
VALUES(?,?,?,?,?,?,?,?,?,NOW())
""", id, proposal.proposalId(), value.reviewTitle(), value.reviewBasis(), actor.actorId(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
updateStatus(actor, proposal, ProposalStatus.IN_REVIEW, value.version());
timeline(actor, proposal.proposalId(), TimelineType.REVIEW_OPENED, "轻量架构评审已开启", requestId);
return id;
}
ReviewView review(long reviewId, long proposalId, Actor actor) {
return one("SELECT review_id,proposal_id,review_title,review_basis,opened_by,create_time FROM da_architecture_review WHERE review_id=? AND proposal_id=? AND organization_id=? AND department_id=?",
this::reviewView, reviewId, proposalId, actor.organizationId(), actor.departmentId());
}
long comment(Actor actor, ProposalView proposal, ReviewView review, CommentCommand value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
jdbc.update("INSERT INTO da_architecture_review_comment(comment_id,review_id,comment_content,actor_id,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,NOW())",
id, review.reviewId(), value.content(), actor.actorId(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
bumpVersion(actor, proposal.proposalId(), value.version());
timeline(actor, proposal.proposalId(), TimelineType.COMMENTED, "评审意见已追加", requestId);
return id;
}
CommentView comment(long id, Actor actor) {
return one("SELECT comment_id,review_id,comment_content,actor_id,create_time FROM da_architecture_review_comment WHERE comment_id=? AND organization_id=? AND department_id=?",
this::commentView, id, actor.organizationId(), actor.departmentId());
}
int commentCount(long reviewId) { return count("da_architecture_review_comment", reviewId); }
CommentPage comments(long reviewId, long proposalId, Actor actor, int pageNum, int pageSize) {
review(reviewId, proposalId, actor);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM da_architecture_review_comment WHERE review_id=? AND organization_id=? AND department_id=?",
Long.class, reviewId, actor.organizationId(), actor.departmentId());
List<CommentView> rows = jdbc.query("SELECT comment_id,review_id,comment_content,actor_id,create_time FROM da_architecture_review_comment WHERE review_id=? AND organization_id=? AND department_id=? ORDER BY create_time ASC,comment_id ASC LIMIT ? OFFSET ?",
this::commentView, reviewId, actor.organizationId(), actor.departmentId(), pageSize, (pageNum - 1) * pageSize);
return new CommentPage(rows, total == null ? 0 : total);
}
long attach(Actor actor, ProposalView proposal, ReviewView review, AttachmentCommand value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("INSERT INTO da_architecture_review_attachment(attachment_id,review_id,file_ref,file_name,file_size,file_sha256,actor_id,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW())",
id, review.reviewId(), value.fileRef(), value.fileName(), value.fileSize(), value.fileSha256(), actor.actorId(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
} catch (DuplicateKeyException exception) { throw ArchitectureGovernanceDomainException.conflict("相同附件引用已存在"); }
bumpVersion(actor, proposal.proposalId(), value.version());
timeline(actor, proposal.proposalId(), TimelineType.ATTACHED, "安全附件逻辑引用已追加", requestId);
return id;
}
AttachmentView attachment(long id, Actor actor) {
return one("SELECT attachment_id,review_id,file_ref,file_name,file_size,file_sha256,actor_id,create_time FROM da_architecture_review_attachment WHERE attachment_id=? AND organization_id=? AND department_id=?",
this::attachmentView, id, actor.organizationId(), actor.departmentId());
}
int attachmentCount(long reviewId) { return count("da_architecture_review_attachment", reviewId); }
AttachmentPage attachments(long reviewId, long proposalId, Actor actor, int pageNum, int pageSize) {
review(reviewId, proposalId, actor);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM da_architecture_review_attachment WHERE review_id=? AND organization_id=? AND department_id=?",
Long.class, reviewId, actor.organizationId(), actor.departmentId());
List<AttachmentView> rows = jdbc.query("SELECT attachment_id,review_id,file_ref,file_name,file_size,file_sha256,actor_id,create_time FROM da_architecture_review_attachment WHERE review_id=? AND organization_id=? AND department_id=? ORDER BY create_time ASC,attachment_id ASC LIMIT ? OFFSET ?",
this::attachmentView, reviewId, actor.organizationId(), actor.departmentId(), pageSize, (pageNum - 1) * pageSize);
return new AttachmentPage(rows, total == null ? 0 : total);
}
long conclude(Actor actor, ProposalView proposal, ReviewView review, ConclusionCommand value, String requestId) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("INSERT INTO da_architecture_review_conclusion(conclusion_id,review_id,conclusion_code,check_run_id,conclusion_basis,actor_id,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,NOW())",
id, review.reviewId(), value.conclusion().name(), value.checkRunId(), value.basis(), actor.actorId(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
} catch (DuplicateKeyException exception) { throw ArchitectureGovernanceDomainException.conflict("评审已经形成结论"); }
updateStatus(actor, proposal, ProposalStatus.CONCLUDED, value.version());
timeline(actor, proposal.proposalId(), TimelineType.CONCLUDED, "形成有依据结论:" + value.conclusion().name(), requestId);
return id;
}
ConclusionView conclusion(long id, Actor actor) {
return one("SELECT conclusion_id,review_id,conclusion_code,check_run_id,conclusion_basis,actor_id,create_time FROM da_architecture_review_conclusion WHERE conclusion_id=? AND organization_id=? AND department_id=?",
this::conclusionView, id, actor.organizationId(), actor.departmentId());
}
ConclusionView conclusionByReview(long reviewId, long proposalId, Actor actor) {
review(reviewId, proposalId, actor);
return jdbc.query("SELECT conclusion_id,review_id,conclusion_code,check_run_id,conclusion_basis,actor_id,create_time FROM da_architecture_review_conclusion WHERE review_id=? AND organization_id=? AND department_id=?",
this::conclusionView, reviewId, actor.organizationId(), actor.departmentId()).stream().findFirst().orElse(null);
}
TimelinePage timeline(long proposalId, Actor actor, int pageNum, int pageSize) {
requireProposal(proposalId, actor);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM da_architecture_timeline WHERE proposal_id=? AND organization_id=? AND department_id=?",
Long.class, proposalId, actor.organizationId(), actor.departmentId());
List<TimelineView> rows = jdbc.query("SELECT timeline_id,proposal_id,event_type,event_summary,request_id,actor_id,create_time FROM da_architecture_timeline WHERE proposal_id=? AND organization_id=? AND department_id=? ORDER BY create_time ASC,timeline_id ASC LIMIT ? OFFSET ?",
this::timelineView, proposalId, actor.organizationId(), actor.departmentId(), pageSize, (pageNum - 1) * pageSize);
return new TimelinePage(rows, total == null ? 0 : total);
}
RequestTicket beginRequest(Actor actor, String method, String path, String key, String hash) {
RequestRecord existing = request(actor, method, path, key);
if (existing != null) return replay(existing, hash);
String requestId = IdGeneratorUtil.nextUUID();
try {
jdbc.update("""
INSERT INTO da_architecture_request(request_record_id,request_id,actor_id,organization_id,department_id,
request_method,request_path,idempotency_key,request_sha256,request_status,response_object_type,
response_object_id,create_dept,create_by,create_time,update_by,update_time,version)
VALUES(?,?,?,?,?,?,?,?,?,'PROCESSING',NULL,NULL,?,?,NOW(),?,NOW(),0)
""", IdGeneratorUtil.nextLongId(), requestId, actor.actorId(), actor.organizationId(), actor.departmentId(),
method, path, key, hash, actor.departmentId(), actor.actorId(), actor.actorId());
return new RequestTicket(requestId, null, null);
} catch (DuplicateKeyException exception) {
RequestRecord raced = request(actor, method, path, key);
if (raced == null) throw ArchitectureGovernanceDomainException.conflict("幂等请求正在处理中");
return replay(raced, hash);
}
}
void completeRequest(Actor actor, String method, String path, String key, ObjectType type, long objectId) {
int changed = jdbc.update("UPDATE da_architecture_request SET request_status='COMPLETED',response_object_type=?,response_object_id=?,update_by=?,update_time=NOW(),version=version+1 WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method=? AND request_path=? AND idempotency_key=? AND request_status='PROCESSING'",
type.name(), objectId, actor.actorId(), actor.actorId(), actor.organizationId(), actor.departmentId(), method, path, key);
requireChanged(changed);
}
private RequestRecord request(Actor actor, String method, String path, String key) {
return jdbc.query("SELECT request_id,request_sha256,request_status,response_object_type,response_object_id FROM da_architecture_request WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method=? AND request_path=? AND idempotency_key=?",
(rs, n) -> new RequestRecord(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getObject(5, Long.class)),
actor.actorId(), actor.organizationId(), actor.departmentId(), method, path, key).stream().findFirst().orElse(null);
}
private static RequestTicket replay(RequestRecord value, String hash) {
if (!value.hash().equals(hash)) throw ArchitectureGovernanceDomainException.conflict("同一幂等键不能用于不同载荷");
if (!"COMPLETED".equals(value.status()) || value.objectId() == null) throw ArchitectureGovernanceDomainException.conflict("幂等请求仍在处理中");
return new RequestTicket(value.requestId(), ObjectType.valueOf(value.objectType()), value.objectId());
}
private void updateStatus(Actor actor, ProposalView proposal, ProposalStatus target, long version) {
int changed = jdbc.update("UPDATE da_architecture_proposal SET proposal_status=?,update_by=?,update_time=NOW(),version=version+1 WHERE proposal_id=? AND proposal_status=? AND version=? AND organization_id=? AND department_id=? AND del_flag='0'",
target.name(), actor.actorId(), proposal.proposalId(), proposal.status().name(), version, actor.organizationId(), actor.departmentId());
requireChanged(changed);
}
private void bumpVersion(Actor actor, long proposalId, long version) {
int changed = jdbc.update("UPDATE da_architecture_proposal SET update_by=?,update_time=NOW(),version=version+1 WHERE proposal_id=? AND version=? AND organization_id=? AND department_id=? AND del_flag='0'",
actor.actorId(), proposalId, version, actor.organizationId(), actor.departmentId());
requireChanged(changed);
}
private int count(String table, long reviewId) {
String sql = switch (table) {
case "da_architecture_review_comment" -> "SELECT COUNT(*) FROM da_architecture_review_comment WHERE review_id=?";
case "da_architecture_review_attachment" -> "SELECT COUNT(*) FROM da_architecture_review_attachment WHERE review_id=?";
default -> throw new IllegalArgumentException("unsupported table");
};
Integer value = jdbc.queryForObject(sql, Integer.class, reviewId);
return value == null ? 0 : value;
}
private void timeline(Actor actor, long proposalId, TimelineType type, String summary, String requestId) {
jdbc.update("INSERT INTO da_architecture_timeline(timeline_id,proposal_id,event_type,event_summary,request_id,actor_id,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,NOW())",
IdGeneratorUtil.nextLongId(), proposalId, type.name(), summary, requestId, actor.actorId(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
}
private void requireProposal(long proposalId, Actor actor) { detail(proposalId, actor); }
private ProposalView proposalView(ResultSet rs, int n) throws SQLException {
return new ProposalView(rs.getLong("proposal_id"), rs.getString("proposal_code"), rs.getString("proposal_name"),
ProposalType.valueOf(rs.getString("proposal_type")), rs.getString("model_logical_id"), rs.getString("model_display_name"),
rs.getString("impact_statement"),
rs.getString("source_ref"), rs.getString("source_version"), rs.getString("payload_sha256"),
policy.readJson(rs.getString("plan_json"), StructuredPlan.class), ProposalStatus.valueOf(rs.getString("proposal_status")),
rs.getLong("organization_id"), rs.getLong("department_id"), rs.getLong("version"),
rs.getObject("create_time", LocalDateTime.class), rs.getObject("update_time", LocalDateTime.class));
}
private RuleSnapshotView snapshotView(ResultSet rs, int n) throws SQLException {
RuleDefinition[] values = policy.readJson(rs.getString("rules_json"), RuleDefinition[].class);
return new RuleSnapshotView(rs.getLong("rule_snapshot_id"), rs.getLong("proposal_id"), rs.getString("source_ref"),
rs.getString("source_version"), rs.getString("payload_sha256"), rs.getString("rules_sha256"), List.of(values),
rs.getObject("create_time", LocalDateTime.class));
}
private CheckRow checkRow(ResultSet rs, int n) throws SQLException {
return new CheckRow(rs.getLong("check_run_id"), rs.getLong("proposal_id"), rs.getLong("rule_snapshot_id"),
rs.getString("input_sha256"), rs.getString("rules_sha256"), CheckStatus.valueOf(rs.getString("overall_status")),
rs.getObject("create_time", LocalDateTime.class));
}
private CheckRunView checkView(CheckRow row) {
List<CheckItemView> items = jdbc.query("SELECT check_item_id,check_run_id,rule_code,rule_type,check_status,reason,expected_value FROM da_architecture_check_item WHERE check_run_id=? ORDER BY rule_code,check_item_id",
(rs, n) -> new CheckItemView(rs.getLong(1), rs.getLong(2), rs.getString(3), RuleType.valueOf(rs.getString(4)),
CheckStatus.valueOf(rs.getString(5)), rs.getString(6), rs.getString(7)), row.checkRunId());
return new CheckRunView(row.checkRunId(), row.proposalId(), row.ruleSnapshotId(), row.inputSha(), row.rulesSha(), row.status(), items, row.createTime());
}
private ReviewView reviewView(ResultSet rs, int n) throws SQLException { return new ReviewView(rs.getLong(1), rs.getLong(2), rs.getString(3), rs.getString(4), rs.getLong(5), rs.getObject(6, LocalDateTime.class)); }
private CommentView commentView(ResultSet rs, int n) throws SQLException { return new CommentView(rs.getLong(1), rs.getLong(2), rs.getString(3), rs.getLong(4), rs.getObject(5, LocalDateTime.class)); }
private ConclusionView conclusionView(ResultSet rs, int n) throws SQLException { return new ConclusionView(rs.getLong(1), rs.getLong(2), ConclusionType.valueOf(rs.getString(3)), rs.getLong(4), rs.getString(5), rs.getLong(6), rs.getObject(7, LocalDateTime.class)); }
private AttachmentView attachmentView(ResultSet rs, int n) throws SQLException { return new AttachmentView(rs.getLong(1), rs.getLong(2), rs.getString(3), rs.getString(4), rs.getLong(5), rs.getString(6), rs.getLong(7), rs.getObject(8, LocalDateTime.class)); }
private TimelineView timelineView(ResultSet rs, int n) throws SQLException { return new TimelineView(rs.getLong(1), rs.getLong(2), TimelineType.valueOf(rs.getString(3)), rs.getString(4), rs.getString(5), rs.getLong(6), rs.getObject(7, LocalDateTime.class)); }
private <T> T one(String sql, org.springframework.jdbc.core.RowMapper<T> mapper, Object... args) {
return jdbc.query(sql, mapper, args).stream().findFirst().orElseThrow(ArchitectureGovernanceDomainException::notFound);
}
private static void requireChanged(int changed) { if (changed != 1) throw ArchitectureGovernanceDomainException.conflict("版本已变化,请刷新后重试"); }
enum ObjectType { PROPOSAL, RULE_SNAPSHOT, CHECK_RUN, REVIEW, COMMENT, CONCLUSION, ATTACHMENT }
record RequestTicket(String requestId, ObjectType objectType, Long objectId) { }
private record RequestRecord(String requestId, String hash, String status, String objectType, Long objectId) { }
private record CheckRow(long checkRunId, long proposalId, long ruleSnapshotId, String inputSha,
String rulesSha, CheckStatus status, LocalDateTime createTime) { }
record ProposalPage(List<ProposalView> rows, long total) { }
record SnapshotPage(List<RuleSnapshotView> rows, long total) { }
record CheckPage(List<CheckRunView> rows, long total) { }
record CommentPage(List<CommentView> rows, long total) { }
record AttachmentPage(List<AttachmentView> rows, long total) { }
record TimelinePage(List<TimelineView> rows, long total) { }
}
@@ -0,0 +1,237 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.regex.Pattern;
@Component
@RequiredArgsConstructor
class ArchitectureGovernancePolicy {
static final int MAX_RULES = 100;
static final int MAX_LIST_VALUES = 100;
static final int MAX_COMMENTS = 500;
static final int MAX_ATTACHMENTS = 20;
static final long MAX_FILE_SIZE = 100L * 1024 * 1024;
static final int MAX_JSON = 262_144;
private static final Pattern CODE = Pattern.compile("[A-Z][A-Z0-9_-]{0,63}");
private static final Pattern LOGICAL_ID = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:-]{0,127}");
private static final Pattern SAFE_REF = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:/-]{0,255}");
private static final Pattern FILE_REF = Pattern.compile("file:[A-Za-z0-9_][A-Za-z0-9_.:/-]{0,250}");
private static final Pattern SHA256 = Pattern.compile("[a-f0-9]{64}");
private static final Pattern IDEMPOTENCY_KEY = Pattern.compile("[A-Za-z0-9._:-]{1,128}");
private static final Pattern FORBIDDEN = Pattern.compile(
"(?is)(https?://|jdbc:|;|--|/\\*|\\*/|<script|javascript:|\\b(password|passwd|token|secret|credential|connection|select|insert|update|delete|drop|alter|create|truncate|merge|call|execute|exec|shell|script|ddl|sql)\\b)");
private final JsonMapper jsonMapper;
String idempotencyKey(String value) {
String normalized = required(value, "Idempotency-Key", 128);
if (!IDEMPOTENCY_KEY.matcher(normalized).matches()) throw validation("Idempotency-Key格式无效");
return normalized;
}
String keyword(String value) { return optional(value, "查询关键词", 200); }
int pageNum(Integer value) { return bounded(value == null ? 1 : value, 1, 100_000, "页码"); }
int pageSize(Integer value) { return bounded(value == null ? 20 : value, 1, 100, "每页条数"); }
CreateProposalCommand normalize(CreateProposalCommand value) {
if (value == null || value.proposalType() == null || value.plan() == null) throw validation("架构方案请求不完整");
StructuredPlan plan = normalize(value.plan());
CreateProposalCommand normalized = new CreateProposalCommand(code(value.proposalCode(), "方案编码"),
required(value.proposalName(), "方案名称", 200), value.proposalType(),
logicalId(value.modelLogicalId(), "模型逻辑引用"), required(value.modelDisplayName(), "模型显示快照", 200),
required(value.impactStatement(), "影响说明", 4000), safeRef(value.sourceRef(), "来源引用"),
required(value.sourceVersion(), "来源版本", 128), null, plan);
String derived = payloadSha(normalized);
if (value.payloadSha256() != null && !value.payloadSha256().isBlank() && !derived.equals(sha(value.payloadSha256(), "payloadSha256"))) throw validation("架构方案payloadSha256与结构化内容不一致");
return new CreateProposalCommand(normalized.proposalCode(), normalized.proposalName(), normalized.proposalType(),
normalized.modelLogicalId(), normalized.modelDisplayName(),
normalized.impactStatement(), normalized.sourceRef(), normalized.sourceVersion(), derived, plan);
}
RuleSnapshotCommand normalize(RuleSnapshotCommand value) {
if (value == null || value.version() == null || value.version() < 0 || value.rules() == null
|| value.rules().isEmpty() || value.rules().size() > MAX_RULES) throw validation("规则快照请求不完整或规则数量超限");
Set<String> codes = new HashSet<>();
EnumSet<RuleType> types = EnumSet.noneOf(RuleType.class);
List<RuleDefinition> rules = value.rules().stream().map(rule -> normalizeRule(rule, codes, types))
.sorted(Comparator.comparing(RuleDefinition::ruleCode)).toList();
if (!types.equals(EnumSet.allOf(RuleType.class))) throw validation("规则快照必须覆盖五类规则");
RuleSnapshotCommand normalized = new RuleSnapshotCommand(safeRef(value.sourceRef(), "规则来源"),
required(value.sourceVersion(), "规则版本", 128), rulesSha(rules), rules, value.version());
if (value.payloadSha256() != null && !value.payloadSha256().isBlank() && !normalized.payloadSha256().equals(sha(value.payloadSha256(), "payloadSha256"))) throw validation("规则payloadSha256与规则内容不一致");
return normalized;
}
CheckCommand normalize(CheckCommand value) {
if (value == null || value.ruleSnapshotId() <= 0 || value.version() == null || value.version() < 0) {
throw validation("检查请求不完整");
}
return new CheckCommand(value.ruleSnapshotId(), sha(value.inputSha256(), "inputSha256"), value.version());
}
ReviewCommand normalize(ReviewCommand value) {
if (value == null || value.version() == null || value.version() < 0) throw validation("评审请求不完整");
return new ReviewCommand(required(value.reviewTitle(), "评审标题", 200),
required(value.reviewBasis(), "评审依据", 4000), value.version());
}
CommentCommand normalize(CommentCommand value) {
if (value == null || value.version() == null || value.version() < 0) throw validation("评审意见请求不完整");
return new CommentCommand(required(value.content(), "评审意见", 2000), value.version());
}
ConclusionCommand normalize(ConclusionCommand value) {
if (value == null || value.conclusion() == null || value.checkRunId() <= 0
|| value.version() == null || value.version() < 0) throw validation("评审结论请求不完整");
return new ConclusionCommand(value.conclusion(), value.checkRunId(), required(value.basis(), "结论依据", 4000), value.version());
}
AttachmentCommand normalize(AttachmentCommand value) {
if (value == null || value.version() == null || value.version() < 0 || value.fileSize() < 0
|| value.fileSize() > MAX_FILE_SIZE) throw validation("附件引用请求不完整或大小超限");
String ref = required(value.fileRef(), "fileRef", 255);
if (!FILE_REF.matcher(ref).matches() || FORBIDDEN.matcher(ref).find()) throw validation("fileRef格式无效");
return new AttachmentCommand(ref, required(value.fileName(), "文件名", 255), value.fileSize(),
sha(value.fileSha256(), "fileSha256"), value.version());
}
List<EvaluatedRule> evaluate(StructuredPlan plan, List<RuleDefinition> rules) {
return rules.stream().map(rule -> evaluate(plan, rule)).toList();
}
CheckStatus overall(List<EvaluatedRule> values) {
if (values.stream().anyMatch(v -> v.status() == CheckStatus.FAIL)) return CheckStatus.FAIL;
if (values.stream().anyMatch(v -> v.status() == CheckStatus.UNKNOWN)) return CheckStatus.UNKNOWN;
return CheckStatus.PASS;
}
void requireConclusion(ConclusionType conclusion, CheckRunView check) {
if (conclusion == ConclusionType.APPROVED && check.overallStatus() != CheckStatus.PASS) {
throw ArchitectureGovernanceDomainException.conflict("检查存在FAIL或UNKNOWN时不得批准");
}
}
String payloadSha(CreateProposalCommand value) {
return sha256(canonical(List.of(value.proposalCode(), value.proposalName(), value.proposalType(),
value.modelLogicalId(), value.modelDisplayName(),
value.impactStatement(), value.sourceRef(), value.sourceVersion(), value.plan())));
}
String planSha(StructuredPlan plan) { return sha256(canonical(plan)); }
String rulesSha(List<RuleDefinition> rules) { return sha256(canonical(rules)); }
String requestHash(Object value) { return sha256(canonical(value)); }
String writeJson(Object value) { return canonical(value); }
<T> T readJson(String value, Class<T> type) {
try { return jsonMapper.readValue(value, type); }
catch (JacksonException exception) { throw new IllegalStateException("架构治理JSON读取失败", exception); }
}
private StructuredPlan normalize(StructuredPlan value) {
List<String> fields = normalizeValues(value.commonFields(), "公共字段");
List<String> tags = normalizeValues(value.securityTags(), "安全标签");
return new StructuredPlan(required(value.objectName(), "对象名称", 128), optional(value.layerCode(), "分层编码", 64),
optional(value.dataType(), "数据类型", 64), fields, tags);
}
private RuleDefinition normalizeRule(RuleDefinition value, Set<String> codes, Set<RuleType> types) {
if (value == null || value.ruleType() == null) throw validation("规则定义不完整");
String ruleCode = code(value.ruleCode(), "规则编码");
if (!codes.add(ruleCode)) throw validation("规则编码重复");
types.add(value.ruleType());
String expected = required(value.expectedValue(), "规则期望值", 1000);
if (FORBIDDEN.matcher(expected).find()) throw validation("规则期望值包含禁止内容");
if (value.ruleType() == RuleType.NAMING) {
try { Pattern.compile(expected); } catch (RuntimeException exception) { throw validation("命名规则正则无效"); }
}
return new RuleDefinition(ruleCode, value.ruleType(), expected, value.required(),
required(value.rationale(), "规则依据", 1000));
}
private EvaluatedRule evaluate(StructuredPlan plan, RuleDefinition rule) {
return switch (rule.ruleType()) {
case NAMING -> result(rule, Pattern.compile(rule.expectedValue()).matcher(plan.objectName()).matches(), false,
"对象名称按规则快照匹配");
case LAYERING -> contains(rule, plan.layerCode(), "分层编码");
case DATA_TYPE -> contains(rule, plan.dataType(), "数据类型");
case COMMON_FIELD -> listContains(rule, plan.commonFields(), "公共字段");
case SECURITY -> listContains(rule, plan.securityTags(), "安全标签");
};
}
private EvaluatedRule contains(RuleDefinition rule, String actual, String label) {
if (actual == null) return unknown(rule, label + "缺少可靠证据");
boolean matched = csv(rule.expectedValue()).contains(actual.toUpperCase(Locale.ROOT));
return result(rule, matched, false, label + (matched ? "符合" : "不符合") + "规则快照");
}
private EvaluatedRule listContains(RuleDefinition rule, List<String> actual, String label) {
if (actual == null || actual.isEmpty()) return unknown(rule, label + "缺少可靠证据");
Set<String> values = actual.stream().map(v -> v.toUpperCase(Locale.ROOT)).collect(java.util.stream.Collectors.toSet());
boolean matched = csv(rule.expectedValue()).stream().allMatch(values::contains);
return result(rule, matched, false, label + (matched ? "符合" : "不符合") + "规则快照");
}
private EvaluatedRule result(RuleDefinition rule, boolean matched, boolean unknown, String reason) {
CheckStatus status = unknown ? CheckStatus.UNKNOWN : matched ? CheckStatus.PASS : CheckStatus.FAIL;
return new EvaluatedRule(rule, status, reason);
}
private EvaluatedRule unknown(RuleDefinition rule, String reason) {
return rule.required() ? new EvaluatedRule(rule, CheckStatus.UNKNOWN, reason)
: new EvaluatedRule(rule, CheckStatus.PASS, "非必需规则且" + reason);
}
private Set<String> csv(String value) {
Set<String> result = new LinkedHashSet<>();
for (String item : value.split(",")) result.add(required(item, "规则枚举值", 128).toUpperCase(Locale.ROOT));
return result;
}
private List<String> normalizeValues(List<String> values, String label) {
if (values == null) return List.of();
if (values.size() > MAX_LIST_VALUES) throw validation(label + "数量超限");
return values.stream().map(v -> required(v, label, 128)).distinct().sorted().toList();
}
private String canonical(Object value) {
try {
String result = jsonMapper.writeValueAsString(value);
if (result.getBytes(StandardCharsets.UTF_8).length > MAX_JSON) throw validation("结构化载荷超出大小边界");
return result;
} catch (JacksonException exception) { throw validation("结构化载荷无法序列化"); }
}
private String code(String value, String label) {
String normalized = required(value, label, 64).toUpperCase(Locale.ROOT);
if (!CODE.matcher(normalized).matches()) throw validation(label + "格式无效");
return normalized;
}
private String logicalId(String value, String label) {
String normalized = required(value, label, 128);
if (!LOGICAL_ID.matcher(normalized).matches()) throw validation(label + "格式无效");
return normalized;
}
private String safeRef(String value, String label) {
String normalized = required(value, label, 256);
if (!SAFE_REF.matcher(normalized).matches() || FORBIDDEN.matcher(normalized).find()) throw validation(label + "格式无效");
return normalized;
}
private String sha(String value, String label) {
String normalized = required(value, label, 64).toLowerCase(Locale.ROOT);
if (!SHA256.matcher(normalized).matches()) throw validation(label + "必须为SHA-256");
return normalized;
}
private String required(String value, String label, int max) {
if (value == null || value.isBlank()) throw validation(label + "不能为空");
String normalized = value.trim();
if (normalized.length() > max || FORBIDDEN.matcher(normalized).find()) throw validation(label + "无效或超出长度边界");
return normalized;
}
private String optional(String value, String label, int max) {
return value == null || value.isBlank() ? null : required(value, label, max);
}
private static int bounded(int value, int min, int max, String label) {
if (value < min || value > max) throw validation(label + "超出范围");
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(exception); }
}
private static ArchitectureGovernanceDomainException validation(String message) {
return ArchitectureGovernanceDomainException.validation(message);
}
record EvaluatedRule(RuleDefinition rule, CheckStatus status, String reason) { }
}
@@ -0,0 +1,200 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceActorProvider.Actor;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceApi.*;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceJdbcRepository.ObjectType;
import cn.aixunkeji.datagov.governance.architecturegovernance.ArchitectureGovernanceJdbcRepository.RequestTicket;
import cn.aixunkeji.datagov.governance.modeldesign.ModelDesignSourceFacade;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.function.Function;
import java.util.function.Supplier;
@Service
@RequiredArgsConstructor
class ArchitectureGovernanceService {
private static final String ROOT = "/api/governance/v1/architecture-governance";
private final ArchitectureGovernanceJdbcRepository repository;
private final ArchitectureGovernancePolicy policy;
private final ArchitectureGovernanceActorProvider actorProvider;
private final TransactionTemplate transactionTemplate;
private final ModelDesignSourceFacade modelDesignSources;
PageResult<ModelDesignSourceFacade.Source> modelSources(String keyword, Integer pageNum, Integer pageSize) {
actorProvider.current();
try { return modelDesignSources.candidates(keyword, pageNum, pageSize); }
catch (ModelDesignSourceFacade.SourceException exception) { throw sourceError(exception); }
}
PageResult<ProposalView> page(String keyword, ProposalStatus status, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var result = repository.page(actor, policy.keyword(keyword), status, policy.pageNum(pageNum), policy.pageSize(pageSize));
return new PageResult<>(result.rows(), result.total());
}
ProposalView detail(long proposalId) { return repository.detail(positive(proposalId), actorProvider.current()); }
CheckRunView checkDetail(long proposalId, long checkRunId) {
return repository.check(positive(checkRunId), positive(proposalId), actorProvider.current());
}
RuleSnapshotView ruleSnapshotDetail(long proposalId, long snapshotId) {
return repository.snapshot(positive(snapshotId), positive(proposalId), actorProvider.current());
}
PageResult<RuleSnapshotView> snapshots(long proposalId, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var result = repository.snapshots(positive(proposalId), actor, policy.pageNum(pageNum), policy.pageSize(pageSize));
return new PageResult<>(result.rows(), result.total());
}
PageResult<CheckRunView> checks(long proposalId, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var result = repository.checks(positive(proposalId), actor, policy.pageNum(pageNum), policy.pageSize(pageSize));
return new PageResult<>(result.rows(), result.total());
}
PageResult<TimelineView> timeline(long proposalId, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var result = repository.timeline(positive(proposalId), actor, policy.pageNum(pageNum), policy.pageSize(pageSize));
return new PageResult<>(result.rows(), result.total());
}
ReviewView review(long proposalId, long reviewId) {
Actor actor = actorProvider.current();
return repository.review(positive(reviewId), positive(proposalId), actor);
}
PageResult<CommentView> comments(long proposalId, long reviewId, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var result = repository.comments(positive(reviewId), positive(proposalId), actor, policy.pageNum(pageNum), policy.pageSize(pageSize));
return new PageResult<>(result.rows(), result.total());
}
PageResult<AttachmentView> attachments(long proposalId, long reviewId, Integer pageNum, Integer pageSize) {
Actor actor = actorProvider.current();
var result = repository.attachments(positive(reviewId), positive(proposalId), actor, policy.pageNum(pageNum), policy.pageSize(pageSize));
return new PageResult<>(result.rows(), result.total());
}
ConclusionView conclusion(long proposalId, long reviewId) {
Actor actor = actorProvider.current();
return repository.conclusionByReview(positive(reviewId), positive(proposalId), actor);
}
WriteView<ProposalView> create(String rawKey, CreateProposalCommand raw) {
Actor actor = actorProvider.current(); CreateProposalCommand value = policy.normalize(raw);
String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", ROOT, key, value, ObjectType.PROPOSAL,
id -> repository.detail(id, actor), () -> {
// The request row is already locked; the Owner row stays locked through the proposal insert.
modelDesignSources.validateForCreate(value.sourceRef(), value.modelLogicalId(),
value.modelDisplayName(), value.sourceVersion());
RequestTicket current = CURRENT.get();
return repository.create(actor, value, current.requestId());
});
}
WriteView<RuleSnapshotView> snapshot(long rawProposalId, String rawKey, RuleSnapshotCommand raw) {
long proposalId = positive(rawProposalId); Actor actor = actorProvider.current(); RuleSnapshotCommand value = policy.normalize(raw);
String path = ROOT + "/" + proposalId + "/rule-snapshots"; String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", path, key, value, ObjectType.RULE_SNAPSHOT,
id -> repository.snapshot(id, proposalId, actor), () -> {
ProposalView proposal = repository.detail(proposalId, actor);
requireVersion(proposal, value.version()); requireStatus(proposal, ProposalStatus.OPEN);
return repository.snapshot(actor, proposal, value, policy.rulesSha(value.rules()), CURRENT.get().requestId());
});
}
WriteView<CheckRunView> check(long rawProposalId, String rawKey, CheckCommand raw) {
long proposalId = positive(rawProposalId); Actor actor = actorProvider.current(); CheckCommand value = policy.normalize(raw);
String path = ROOT + "/" + proposalId + "/checks"; String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", path, key, value, ObjectType.CHECK_RUN,
id -> repository.check(id, proposalId, actor), () -> {
ProposalView proposal = repository.detail(proposalId, actor);
requireVersion(proposal, value.version()); requireStatus(proposal, ProposalStatus.OPEN);
if (!proposal.payloadSha256().equals(value.inputSha256())) {
throw ArchitectureGovernanceDomainException.validation("inputSha256与架构方案快照不一致");
}
RuleSnapshotView snapshot = repository.snapshot(value.ruleSnapshotId(), proposalId, actor);
var evaluated = policy.evaluate(proposal.plan(), snapshot.rules());
return repository.check(actor, proposal, snapshot, value.inputSha256(), evaluated,
policy.overall(evaluated), CURRENT.get().requestId());
});
}
WriteView<ReviewView> review(long rawProposalId, String rawKey, ReviewCommand raw) {
long proposalId = positive(rawProposalId); Actor actor = actorProvider.current(); ReviewCommand value = policy.normalize(raw);
String path = ROOT + "/" + proposalId + "/reviews"; String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", path, key, value, ObjectType.REVIEW,
id -> repository.review(id, proposalId, actor), () -> {
ProposalView proposal = repository.detail(proposalId, actor);
requireVersion(proposal, value.version()); requireStatus(proposal, ProposalStatus.OPEN);
if (repository.checks(proposalId, actor, 1, 1).total() == 0) {
throw ArchitectureGovernanceDomainException.conflict("没有不可变检查结果时不得开启评审");
}
return repository.review(actor, proposal, value, CURRENT.get().requestId());
});
}
WriteView<CommentView> comment(long rawProposalId, long rawReviewId, String rawKey, CommentCommand raw) {
long proposalId = positive(rawProposalId); long reviewId = positive(rawReviewId); Actor actor = actorProvider.current();
CommentCommand value = policy.normalize(raw); String path = ROOT + "/" + proposalId + "/reviews/" + reviewId + "/comments";
String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", path, key, value, ObjectType.COMMENT, id -> repository.comment(id, actor), () -> {
ProposalView proposal = repository.detail(proposalId, actor); requireVersion(proposal, value.version()); requireStatus(proposal, ProposalStatus.IN_REVIEW);
ReviewView review = repository.review(reviewId, proposalId, actor);
if (repository.commentCount(reviewId) >= ArchitectureGovernancePolicy.MAX_COMMENTS) throw ArchitectureGovernanceDomainException.validation("评审意见数量已达上限");
return repository.comment(actor, proposal, review, value, CURRENT.get().requestId());
});
}
WriteView<AttachmentView> attach(long rawProposalId, long rawReviewId, String rawKey, AttachmentCommand raw) {
long proposalId = positive(rawProposalId); long reviewId = positive(rawReviewId); Actor actor = actorProvider.current();
AttachmentCommand value = policy.normalize(raw); String path = ROOT + "/" + proposalId + "/reviews/" + reviewId + "/attachments";
String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", path, key, value, ObjectType.ATTACHMENT, id -> repository.attachment(id, actor), () -> {
ProposalView proposal = repository.detail(proposalId, actor); requireVersion(proposal, value.version()); requireStatus(proposal, ProposalStatus.IN_REVIEW);
ReviewView review = repository.review(reviewId, proposalId, actor);
if (repository.attachmentCount(reviewId) >= ArchitectureGovernancePolicy.MAX_ATTACHMENTS) throw ArchitectureGovernanceDomainException.validation("附件引用数量已达上限");
return repository.attach(actor, proposal, review, value, CURRENT.get().requestId());
});
}
WriteView<ConclusionView> conclude(long rawProposalId, long rawReviewId, String rawKey, ConclusionCommand raw) {
long proposalId = positive(rawProposalId); long reviewId = positive(rawReviewId); Actor actor = actorProvider.current();
ConclusionCommand value = policy.normalize(raw); String path = ROOT + "/" + proposalId + "/reviews/" + reviewId + "/conclusion";
String key = policy.idempotencyKey(rawKey);
return write(actor, "POST", path, key, value, ObjectType.CONCLUSION, id -> repository.conclusion(id, actor), () -> {
ProposalView proposal = repository.detail(proposalId, actor); requireVersion(proposal, value.version()); requireStatus(proposal, ProposalStatus.IN_REVIEW);
ReviewView review = repository.review(reviewId, proposalId, actor);
CheckRunView check = repository.check(value.checkRunId(), proposalId, actor);
policy.requireConclusion(value.conclusion(), check);
return repository.conclude(actor, proposal, review, value, CURRENT.get().requestId());
});
}
private static final ThreadLocal<RequestTicket> CURRENT = new ThreadLocal<>();
private <T> WriteView<T> write(Actor actor, String method, String path, String key, Object command,
ObjectType expected, Function<Long, T> replayLoader, Supplier<Long> mutation) {
WriteView<T> result = transactionTemplate.execute(status -> {
RequestTicket ticket = repository.beginRequest(actor, method, path, key, policy.requestHash(command));
if (ticket.objectId() != null) {
if (ticket.objectType() != expected) throw ArchitectureGovernanceDomainException.conflict("幂等结果类型冲突");
return new WriteView<>(ticket.requestId(), replayLoader.apply(ticket.objectId()));
}
CURRENT.set(ticket);
try {
long id = mutation.get();
repository.completeRequest(actor, method, path, key, expected, id);
return new WriteView<>(ticket.requestId(), replayLoader.apply(id));
} catch (ModelDesignSourceFacade.SourceException exception) {
throw sourceError(exception);
} finally { CURRENT.remove(); }
});
if (result == null) throw new IllegalStateException("架构治理事务未返回结果");
return result;
}
private static void requireVersion(ProposalView proposal, long supplied) {
if (proposal.version() != supplied) throw ArchitectureGovernanceDomainException.conflict("架构方案版本已变化");
}
private static ArchitectureGovernanceDomainException sourceError(ModelDesignSourceFacade.SourceException exception) {
if (exception.code() == 403) return ArchitectureGovernanceDomainException.forbidden();
if (exception.code() == 503) return ArchitectureGovernanceDomainException.unavailable();
return ArchitectureGovernanceDomainException.conflict(exception.getMessage());
}
private static void requireStatus(ProposalView proposal, ProposalStatus expected) {
if (proposal.status() != expected) throw ArchitectureGovernanceDomainException.conflict("架构方案状态不允许当前操作");
}
private static long positive(long value) {
if (value <= 0) throw ArchitectureGovernanceDomainException.validation("对象ID无效");
return value;
}
}
@@ -0,0 +1,24 @@
package cn.aixunkeji.datagov.governance.architecturegovernance;
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 P52OwnerContext implements PageAssistContextReader {
private final ArchitectureGovernanceService service;
private final ArchitectureCheckEvidence evidence;
@Override public String pageId(){return "P52";}
@Override public Snapshot read(Request r){
qualifiers(r,"checkRunId","checkItemId");var v=service.detail(numeric(r));
String run=qualifier(r,"checkRunId"),item=qualifier(r,"checkItemId");
if(run==null&&item==null)return snapshot(r,v.version(),"status",v.status(),"version",v.version(),"proposalType",v.proposalType(),"updateTime",v.updateTime(),"selectionState","PROPOSAL_ONLY","sourceVerification","NOT_VERIFIED");
if(run==null||item==null)throw denied();
long runId=ArchitectureCheckEvidence.id(run),itemId=ArchitectureCheckEvidence.id(item);
var check=service.checkDetail(v.proposalId(),runId);
if(check==null||check.checkRunId()!=runId)throw denied();
return evidence.project(r,v,check,service.ruleSnapshotDetail(v.proposalId(),check.ruleSnapshotId()),itemId);
}
}
@@ -0,0 +1,48 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.util.HashSet;
import java.util.Set;
@Component
class AssetCatalogActorProvider {
@DubboReference(check=false,timeout=3000,retries=0) private RemoteUserService users;
Actor current() {
var workflow = cn.aixunkeji.datagov.governance.scheduling.WorkflowExecutionContext.current();
boolean registration = workflow != null && "ASSET_REGISTER".equals(workflow.type());
Long actorId = registration ? workflow.actorId() : LoginHelper.getUserId();
Long departmentId = registration ? workflow.orgId() : LoginHelper.getDeptId();
if (actorId == null || departmentId == null || actorId <= 0 || departmentId <= 0) {
throw AssetCatalogDomainException.forbidden();
}
var proof=users.resolveCatalogPolicySubjects(actorId,departmentId);var now=java.time.Instant.now();
if(proof==null||!proof.allowed()||proof.userId()!=actorId||proof.deptId()!=departmentId||proof.subjectRefs()==null||proof.checkedAt()==null||proof.checkedAt().isBefore(now.minusSeconds(10))||proof.checkedAt().isAfter(now.plusSeconds(5)))throw AssetCatalogDomainException.forbidden();
Set<String> roles=new HashSet<>();for(String ref:proof.subjectRefs())if(ref!=null&&ref.startsWith("ROLE:")&&ref.length()>5&&ref.length()<=105)roles.add(ref.substring(5));
boolean administrator=trusted(users.resolveAssetActor(actorId,departmentId,"ASSET_CATALOG_PERMISSION"),actorId,departmentId,"ASSET_CATALOG_PERMISSION");
return new Actor(actorId,departmentId,departmentId,administrator?Set.of("aixun:governance:asset-catalog:permission"):Set.of(),Set.copyOf(roles));
}
void require(String purpose) {Long actor=LoginHelper.getUserId(),dept=LoginHelper.getDeptId();if(actor==null||dept==null||!Set.of("ASSET_CATALOG_VIEW","ASSET_CATALOG_CREATE","ASSET_CATALOG_UPDATE","ASSET_CATALOG_IDENTITY_VIEW","ASSET_CATALOG_IDENTITY_LINK","ASSET_CATALOG_MODEL_VIEW","ASSET_CATALOG_MODEL_LINK","ASSET_CATALOG_DATASET_VIEW","ASSET_CATALOG_DATASET_LINK","ASSET_CATALOG_API_VIEW","ASSET_CATALOG_API_LINK","ASSET_CATALOG_REPORT_VIEW","ASSET_CATALOG_REPORT_LINK","ASSET_CATALOG_FILE_VIEW","ASSET_CATALOG_FILE_LINK").contains(purpose)||!trusted(users.resolveAssetActor(actor,dept,purpose),actor,dept,purpose))throw AssetCatalogDomainException.forbidden();}
void requireCurrent(Actor actor,String purpose){require(purpose);if(!actor.equals(current()))throw AssetCatalogDomainException.forbidden();}
private static boolean trusted(RemoteUserService.AssetActorDecision grant,long actor,long dept,String purpose){var now=java.time.Instant.now();return grant!=null&&grant.allowed()&&grant.userId()==actor&&grant.deptId()==dept&&purpose.equals(grant.purpose())&&grant.checkedAt()!=null&&!grant.checkedAt().isBefore(now.minusSeconds(10))&&!grant.checkedAt().isAfter(now.plusSeconds(5));}
record Actor(long actorId, long organizationId, long departmentId,
Set<String> permissions, Set<String> roles) {
boolean administrator() {
return permissions.contains("aixun:governance:asset-catalog:permission")
|| permissions.contains("*:*:*");
}
Set<String> subjectRefs() {
Set<String> refs = new HashSet<>();
refs.add("USER:" + actorId);
refs.add("ORGANIZATION:" + organizationId);
refs.add("DEPARTMENT:" + departmentId);
roles.forEach(role -> refs.add("ROLE:" + role));
return Set.copyOf(refs);
}
}
}
@@ -0,0 +1,54 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import java.time.LocalDateTime;
import java.util.List;
final class AssetCatalogApi {
private AssetCatalogApi() { }
enum CatalogStatus { DRAFT, PUBLISHED, UNPUBLISHED }
enum AssetType { TABLE, DATASET, FILE, REPORT, API, MODEL }
enum SubjectType { USER, ROLE, ORGANIZATION, DEPARTMENT }
enum CatalogAction { VIEW, MAINTAIN, PUBLISH, PERMISSION }
record CreateNodeCommand(String catalogCode, String catalogName, Long parentId,
String description, Integer sortOrder) { }
record UpdateNodeCommand(String catalogName, String description, Integer sortOrder,
Long version) { }
record MoveNodeCommand(Long parentId, Integer sortOrder, Long version) { }
record CatalogAssetCommand(String assetRef, String assetFqn, AssetType assetType,
String assetName, String description, List<String> tags,
String ownerType, String ownerRef, String sourceType,
String sourceRef, LocalDateTime observedAt, boolean reliable,
String payloadSha256, Long version) { }
record InventoryCatalogCommand(long taskId, long candidateId, long candidateVersion, Long version) { }
record PublishCommand(String reason, Long version) { }
record StatusCommand(CatalogStatus targetStatus, String reason, Long version) { }
record PermissionCommand(SubjectType subjectType, String subjectRef,
List<CatalogAction> actions, boolean includeDescendants,
LocalDateTime effectiveFrom, LocalDateTime effectiveTo,
String reason, Long version) { }
record NodeView(long catalogId, String catalogCode, String catalogName, Long parentId,
String description, int sortOrder, CatalogStatus status,
long organizationId, long departmentId, long version,
LocalDateTime createTime, LocalDateTime updateTime) { }
record AssetView(long catalogAssetId, long catalogId, String assetRef, String assetFqn,
AssetType assetType, String assetName, String description, List<String> tags,
String ownerType, String ownerRef, String sourceType, String sourceRef,
LocalDateTime observedAt, boolean reliable, String payloadSha256,
long version, LocalDateTime createTime) { }
record PublicationView(long publicationId, long catalogId, long publicationVersion,
String snapshotSha256, int itemCount, String reason,
long actorId, LocalDateTime createTime) { }
record PermissionView(long permissionId, long catalogId, SubjectType subjectType,
String subjectRef, List<CatalogAction> actions,
boolean includeDescendants, LocalDateTime effectiveFrom,
LocalDateTime effectiveTo, long version, LocalDateTime createTime) { }
record TrajectoryView(long trajectoryId, long catalogId, String actionType,
String beforeStatus, String afterStatus, String requestId,
long actorId, String summary, LocalDateTime createTime) { }
record DetailView(NodeView node, List<AssetView> assets, List<PublicationView> publications,
List<PermissionView> permissions, List<TrajectoryView> trajectories) { }
record WriteView<T>(String requestId, T result) { }
}
@@ -0,0 +1,10 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.governance.api.assetcatalog.AssetCatalogAssistDirectory.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/governance/v1/asset-catalogs/assist")
public class AssetCatalogAssistController {
private final AssetCatalogAssistService service;public AssetCatalogAssistController(AssetCatalogAssistService service){this.service=service;}
@PostMapping("/context") @SaCheckPermission("aixun:governance:asset-catalog:view") public R<Context> current(@RequestBody Selection selection){return R.ok(service.current(selection));}
}
@@ -0,0 +1,8 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.api.assetcatalog.AssetCatalogAssistDirectory;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService(version=AssetCatalogAssistDirectory.VERSION,timeout=30000,retries=0)
public class AssetCatalogAssistDubboService implements AssetCatalogAssistDirectory {
private final AssetCatalogAssistService service;public AssetCatalogAssistDubboService(AssetCatalogAssistService service){this.service=service;}
public Context current(Selection selection){return service.current(selection);}
}
@@ -0,0 +1,9 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.api.assetcatalog.AssetCatalogAssistDirectory.*;
import java.text.Normalizer;
import java.util.*;
final class AssetCatalogAssistPolicy {
static Selection selection(Selection raw){if(raw==null||!Set.of("CREATE","UPDATE","MOVE").contains(raw.mode())||raw.nodeIds()==null||raw.nodeIds().isEmpty()||raw.nodeIds().size()>30||raw.nodeIds().stream().anyMatch(id->id==null||id<1)||new HashSet<>(raw.nodeIds()).size()!=raw.nodeIds().size()||("CREATE".equals(raw.mode())?raw.objectId()!=null:raw.objectId()==null||raw.objectId()<1))throw AssetCatalogDomainException.validation("请选择最多30个当前目录,明确新增、编辑或移动对象");var ids=new TreeSet<>(raw.nodeIds());if(raw.objectId()!=null)ids.add(raw.objectId());if(ids.size()>30)throw AssetCatalogDomainException.validation("所选目录包含当前节点后不能超过30个");return new Selection(raw.mode(),raw.objectId(),List.copyOf(ids));}
static List<Collision> collisions(List<Node> nodes){var result=new ArrayList<Collision>();for(int i=0;i<nodes.size();i++)for(int j=i+1;j<nodes.size();j++){var a=nodes.get(i);var b=nodes.get(j);if(normalize(a.name()).equals(normalize(b.name())))result.add(new Collision(a.key(),b.key(),"NORMALIZED_NAME_EQUAL"));}return List.copyOf(result);}
private static String normalize(String text){return Normalizer.normalize(text==null?"":text,Normalizer.Form.NFKC).strip().replaceAll("\\s+"," ").toLowerCase(Locale.ROOT);}
}
@@ -0,0 +1,21 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.api.assetcatalog.AssetCatalogAssistDirectory;
import org.springframework.stereotype.Service;
import tools.jackson.databind.ObjectMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
@Service
class AssetCatalogAssistService implements AssetCatalogAssistDirectory {
private final AssetCatalogActorProvider actors;private final AssetCatalogJdbcRepository repository;private final ObjectMapper json;
AssetCatalogAssistService(AssetCatalogActorProvider actors,AssetCatalogJdbcRepository repository,ObjectMapper json){this.actors=actors;this.repository=repository;this.json=json;}
public Context current(Selection raw){var selection=AssetCatalogAssistPolicy.selection(raw);String purpose="CREATE".equals(selection.mode())?"ASSET_CATALOG_CREATE":"ASSET_CATALOG_UPDATE";actors.require(purpose);var actor=actors.current();var first=read(actor,selection);var second=read(actor,selection);actors.requireCurrent(actor,purpose);if(!first.equals(second))throw AssetCatalogDomainException.conflict("目录关系、版本或权限已变化,请重新核对");return first;}
private Context read(AssetCatalogActorProvider.Actor actor,Selection selection){
var originals=new ArrayList<AssetCatalogApi.NodeView>();for(long id:selection.nodeIds()){repository.authorize(actor,id,AssetCatalogApi.CatalogAction.VIEW);originals.add(repository.node(id,actor));}
if(selection.objectId()!=null){repository.authorize(actor,selection.objectId(),AssetCatalogApi.CatalogAction.MAINTAIN);var current=originals.stream().filter(n->n.catalogId()==selection.objectId()).findFirst().orElseThrow(AssetCatalogDomainException::notFound);if(current.status()==AssetCatalogApi.CatalogStatus.PUBLISHED)throw AssetCatalogDomainException.conflict("已发布目录不能直接调整,请先按原流程下线");}
var keys=new HashMap<Long,String>();for(int i=0;i<originals.size();i++)keys.put(originals.get(i).catalogId(),"N"+(i+1));var nodes=new ArrayList<Node>();
for(var n:originals){boolean eligible=!"UPDATE".equals(selection.mode())&&repository.eligibleParent(actor,selection.objectId(),n.catalogId());nodes.add(new Node(keys.get(n.catalogId()),n.catalogId(),n.version(),n.catalogName(),n.description(),n.parentId()==null?null:keys.get(n.parentId()),n.parentId()==null||keys.containsKey(n.parentId()),eligible));}
boolean root="CREATE".equals(selection.mode())?actor.administrator():"MOVE".equals(selection.mode());String hash=hash(List.of(selection,originals,nodes,actor.actorId(),actor.departmentId(),new TreeSet<>(actor.subjectRefs()),root));return new Context(selection,List.copyOf(nodes),AssetCatalogAssistPolicy.collisions(nodes),root,"仅核对本次所选目录;未选择或不可见的祖先与其他目录未纳入,不能据此断言全目录没有重复。同名是线索,不代表业务等价。候选不会移动、合并或发布目录。",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);}}
}
@@ -0,0 +1,113 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
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.governance.assetcatalog.AssetCatalogApi.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/governance/v1/asset-catalogs")
public class AssetCatalogController {
private final AssetCatalogService service;
private final AssetCatalogOverviewReader overview;
private final AssetCatalogIdentitySummaryReader identitySummary;
@SaCheckPermission("aixun:governance:asset-catalog:view")
@GetMapping("/identity-summary")
public R<AssetCatalogIdentitySummaryReader.Summary> identitySummary(@RequestParam(required=false) Long catalogId) {
return R.ok(identitySummary.read(catalogId));
}
@SaCheckPermission("aixun:governance:asset-catalog:view")
@GetMapping("/overview")
public R<AssetCatalogOverviewReader.Portfolio> overview() { return R.ok(overview.portfolio()); }
@SaCheckPermission("aixun:governance:asset-catalog:view")
@GetMapping("/registrations")
public R<AssetCatalogOverviewReader.Registrations> registrations(@RequestParam(required = false) Long catalogId) {
return R.ok(overview.registrations(catalogId));
}
@SaCheckPermission("aixun:governance:asset-catalog:view")
@GetMapping
public R<List<NodeView>> tree() { return R.ok(service.tree()); }
@SaCheckPermission("aixun:governance:asset-catalog:view")
@GetMapping("/{catalogId}")
public R<DetailView> detail(@PathVariable long catalogId) { return R.ok(service.detail(catalogId)); }
@Log(title = "资产目录创建", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:create")
@PostMapping
public R<WriteView<DetailView>> create(@RequestHeader("Idempotency-Key") String key,
@RequestBody CreateNodeCommand command) {
return R.ok(service.create(key, command));
}
@Log(title = "资产目录更新", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:update")
@PatchMapping("/{catalogId}")
public R<WriteView<DetailView>> update(@PathVariable long catalogId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody UpdateNodeCommand command) {
return R.ok(service.update(catalogId, key, command));
}
@Log(title = "资产目录移动", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:update")
@PutMapping("/{catalogId}/parent")
public R<WriteView<DetailView>> move(@PathVariable long catalogId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody MoveNodeCommand command) {
return R.ok(service.move(catalogId, key, command));
}
@Log(title = "资产编目", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:catalog")
@PostMapping("/{catalogId}/assets")
public R<WriteView<DetailView>> catalog(@PathVariable long catalogId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody CatalogAssetCommand command) {
return R.ok(service.catalog(catalogId, key, command));
}
@Log(title = "盘点资产编目", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission(value = {"aixun:governance:asset-catalog:catalog", "aixun:governance:asset-inventory:view"}, mode = cn.dev33.satoken.annotation.SaMode.AND)
@PostMapping("/{catalogId}/inventory-assets")
public R<WriteView<DetailView>> catalogFromInventory(@PathVariable long catalogId, @RequestHeader("Idempotency-Key") String key,
@RequestBody InventoryCatalogCommand command) {
return R.ok(service.catalogFromInventory(catalogId, key, command));
}
@Log(title = "资产目录发布", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:publish")
@PostMapping("/{catalogId}/publications")
public R<WriteView<PublicationView>> publish(@PathVariable long catalogId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody PublishCommand command) {
return R.ok(service.publish(catalogId, key, command));
}
@Log(title = "资产目录权限", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:permission")
@PostMapping("/{catalogId}/permissions")
public R<WriteView<PermissionView>> permission(@PathVariable long catalogId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody PermissionCommand command) {
return R.ok(service.permission(catalogId, key, command));
}
@Log(title = "资产目录状态", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-catalog:status")
@PostMapping("/{catalogId}/status")
public R<WriteView<DetailView>> status(@PathVariable long catalogId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody StatusCommand command) {
return R.ok(service.status(catalogId, key, command));
}
}
@@ -0,0 +1,30 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import org.springframework.http.HttpStatus;
final class AssetCatalogDomainException extends RuntimeException {
static final int VALIDATION_CODE = 136101;
static final int FORBIDDEN_CODE = 136103;
static final int NOT_FOUND_CODE = 136104;
static final int CONFLICT_CODE = 136109;
private final int code;
private final HttpStatus status;
private AssetCatalogDomainException(int code, HttpStatus status, String message) {
super(message); this.code = code; this.status = status;
}
static AssetCatalogDomainException validation(String message) {
return new AssetCatalogDomainException(VALIDATION_CODE, HttpStatus.BAD_REQUEST, message);
}
static AssetCatalogDomainException forbidden() {
return new AssetCatalogDomainException(FORBIDDEN_CODE, HttpStatus.FORBIDDEN, "无权访问资产目录资源");
}
static AssetCatalogDomainException notFound() {
return new AssetCatalogDomainException(NOT_FOUND_CODE, HttpStatus.NOT_FOUND, "资产目录资源不存在");
}
static AssetCatalogDomainException conflict(String message) {
return new AssetCatalogDomainException(CONFLICT_CODE, HttpStatus.CONFLICT, message);
}
int code() { return code; }
HttpStatus status() { return status; }
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
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 = {AssetCatalogController.class,AssetCatalogAssistController.class,AssetCatalogIdentityLinkController.class})
class AssetCatalogExceptionHandler {
@ExceptionHandler(AssetCatalogDomainException.class)
ResponseEntity<R<Void>> handle(AssetCatalogDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,29 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.log.annotation.Log;
import cn.aixunkeji.common.log.enums.BusinessType;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/governance/v1/asset-catalogs/registrations/{registrationId}/identity-link")
public class AssetCatalogIdentityLinkController {
private final AssetCatalogIdentityLinkService service;
@GetMapping
@SaCheckPermission(value={"aixun:governance:asset-catalog:view","aixun:governance:asset-detail:view","aixun:governance:asset-lifecycle:view"},mode=SaMode.AND)
public R<AssetCatalogIdentityLinkService.Inspection> inspect(@PathVariable long registrationId){return R.ok(service.inspect(registrationId));}
@PostMapping
@Log(title="编目身份关联",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
@SaCheckPermission(value={"aixun:governance:asset-catalog:view","aixun:governance:asset-catalog:catalog","aixun:governance:asset-detail:view","aixun:governance:asset-lifecycle:view"},mode=SaMode.AND)
public R<AssetCatalogIdentityLinkService.LinkView> link(@PathVariable long registrationId,@RequestHeader("Idempotency-Key")String key,@RequestBody AssetCatalogIdentityLinkService.Command command){return R.ok(service.link(registrationId,key,command));}
@GetMapping("/requests/{key}")
@SaCheckPermission(value={"aixun:governance:asset-catalog:view","aixun:governance:asset-detail:view","aixun:governance:asset-lifecycle:view"},mode=SaMode.AND)
public R<AssetCatalogIdentityLinkService.Receipt> request(@PathVariable long registrationId,@PathVariable String key){return R.ok(service.request(registrationId,key));}
@PostMapping("/requests/{key}/cancel")
@Log(title="结束未提交身份关联请求",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
@SaCheckPermission(value={"aixun:governance:asset-catalog:view","aixun:governance:asset-catalog:catalog","aixun:governance:asset-detail:view","aixun:governance:asset-lifecycle:view"},mode=SaMode.AND)
public R<AssetCatalogIdentityLinkService.Receipt> cancel(@PathVariable long registrationId,@PathVariable String key){return R.ok(service.cancel(registrationId,key));}
}
@@ -0,0 +1,54 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Objects;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogActorProvider.Actor;
@Repository
@RequiredArgsConstructor
class AssetCatalogIdentityLinkRepository {
private final JdbcTemplate jdbc;
record Registration(long id,long catalogId,String assetRef,long version,String type) { }
record Link(long id,long registrationId,long catalogId,long registrationVersion,long version,
String assetRef,long assetId,long businessVersion,String evidenceSha256,Instant expiresAt,
Instant linkedAt,String requestId) { }
record Request(String requestId,String hash,String status,Long responseId) { }
Registration registration(Actor actor,long id,boolean lock) {
return jdbc.query("SELECT catalog_asset_id,catalog_id,asset_ref,version,asset_type FROM asset_catalog_item WHERE catalog_asset_id=? AND organization_id=? AND department_id=? AND del_flag='0'"+(lock?" FOR UPDATE":""),
(r,n)->new Registration(r.getLong(1),r.getLong(2),r.getString(3),r.getLong(4),r.getString(5)),id,actor.organizationId(),actor.departmentId())
.stream().findFirst().orElseThrow(AssetCatalogDomainException::notFound);
}
Link latest(Actor actor,long id) { return find(actor,"catalog_asset_id=? ORDER BY link_version DESC LIMIT 1",id); }
Link get(Actor actor,long id) { return Objects.requireNonNull(find(actor,"link_id=?",id),"身份关联回执丢失"); }
private Link find(Actor actor,String condition,long id) {
return jdbc.query("SELECT link_id,catalog_asset_id,catalog_id,registration_version,link_version,asset_ref,asset_id,business_version,evidence_sha256,evidence_expires_at,create_time,request_id FROM asset_catalog_identity_link WHERE organization_id=? AND department_id=? AND "+condition,
(r,n)->new Link(r.getLong(1),r.getLong(2),r.getLong(3),r.getLong(4),r.getLong(5),r.getString(6),r.getLong(7),r.getLong(8),r.getString(9),r.getTimestamp(10).toInstant(),r.getTimestamp(11).toInstant(),r.getString(12)),actor.organizationId(),actor.departmentId(),id).stream().findFirst().orElse(null);
}
AssetCatalogJdbcRepository.RequestTicket receipt(Actor actor,String path,String key) {
return jdbc.query("SELECT request_id,request_sha256,response_id FROM asset_catalog_request WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method='POST' AND request_path=? AND idempotency_key=? AND request_status='COMPLETED' AND response_id IS NOT NULL",
(r,n)->new AssetCatalogJdbcRepository.RequestTicket(r.getString(1),r.getString(2),r.getLong(3)),actor.actorId(),actor.organizationId(),actor.departmentId(),path,key).stream().findFirst().orElse(null);
}
Request request(Actor actor,String path,String key) {
return jdbc.query("SELECT request_id,request_sha256,request_status,response_id FROM asset_catalog_request WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method='POST' AND request_path=? AND idempotency_key=?",
(r,n)->new Request(r.getString(1),r.getString(2),r.getString(3),r.getObject(4,Long.class)),actor.actorId(),actor.organizationId(),actor.departmentId(),path,key).stream().findFirst().orElse(null);
}
/** The caller holds the same registration lock as link(); never replace an observed request. */
Request cancelUnobserved(Actor actor,String path,String key,String hash) {
long id=IdGeneratorUtil.nextLongId();String requestId="ACR-"+id;
int inserted=jdbc.update("INSERT INTO asset_catalog_request(request_record_id,request_id,actor_id,request_method,request_path,idempotency_key,request_sha256,request_status,organization_id,department_id,create_time) VALUES(?,?,?,'POST',?,?,?,'FAILED',?,?,NOW())",
id,requestId,actor.actorId(),path,key,hash,actor.organizationId(),actor.departmentId());
if(inserted!=1)throw AssetCatalogDomainException.conflict("请求状态已变化,请读取原请求");
return new Request(requestId,hash,"FAILED",null);
}
Link insert(Actor actor,Registration registration,long version,AssetCatalogIdentityLinkService.Proof proof,String evidenceJson,String requestId) {
long id=IdGeneratorUtil.nextLongId();
jdbc.update("INSERT INTO asset_catalog_identity_link(link_id,catalog_asset_id,catalog_id,registration_version,link_version,asset_ref,asset_id,business_version,evidence_json,evidence_sha256,evidence_expires_at,actor_id,organization_id,department_id,request_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
id,registration.id(),registration.catalogId(),registration.version(),version,registration.assetRef(),proof.identity().assetId(),proof.identity().businessVersion(),evidenceJson,proof.sha256(),Timestamp.from(proof.expiresAt()),actor.actorId(),actor.organizationId(),actor.departmentId(),requestId,actor.departmentId(),actor.actorId(),actor.actorId());
return get(actor,id);
}
}
@@ -0,0 +1,159 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.assetidentity.AssetIdentityService;
import cn.aixunkeji.datagov.governance.assetidentity.AssetIdentityModel;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import tools.jackson.databind.json.JsonMapper;
import java.time.Instant;
import java.util.Comparator;
import java.util.Objects;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.CatalogAction;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogActorProvider.Actor;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogIdentityLinkRepository.*;
/** The association records a checked observation; it never merges assets or grants use rights. */
@Service
class AssetCatalogIdentityLinkService {
private final AssetCatalogActorProvider actors;
private final AssetCatalogJdbcRepository catalogs;
private final AssetCatalogIdentityLinkRepository repository;
private final AssetIdentityService identities;
private final AssetCatalogPolicy policy;
private final TransactionTemplate transactions;
private final JsonMapper mapper;
AssetCatalogIdentityLinkService(AssetCatalogActorProvider actors,AssetCatalogJdbcRepository catalogs,
AssetCatalogIdentityLinkRepository repository,AssetIdentityService identities,AssetCatalogPolicy policy,
TransactionTemplate transactions,JsonMapper mapper) {
this.actors=actors;this.catalogs=catalogs;this.repository=repository;this.identities=identities;this.policy=policy;this.mapper=mapper;
this.transactions=new TransactionTemplate(Objects.requireNonNull(transactions.getTransactionManager()),transactions);
this.transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
}
record Command(Long registrationVersion,Long expectedLinkVersion,String assetId,Long businessVersion,String evidenceSha256) { }
record Candidate(String assetId,String businessVersion,String evidenceSha256,Instant expiresAt) { }
record LinkView(String linkId,String registrationId,String version,String assetId,String businessVersion,
String evidenceSha256,Instant expiresAt,Instant linkedAt,String requestId) { }
record Inspection(String registrationId,String registrationVersion,String assetRef,String resolutionState,
String associationState,Candidate candidate,LinkView link,Instant readAt,String unavailableReason) { }
record Receipt(String state,String registrationId,String requestKey,LinkView link) { }
record Proof(AssetIdentity identity,String sha256,Instant expiresAt) { }
Inspection inspect(long id) {
Actor actor=actor("ASSET_CATALOG_IDENTITY_VIEW");
Registration before=registration(actor,id,CatalogAction.VIEW,false);
AssetResolution resolution="TABLE".equals(before.type())?resolve(before.assetRef()):null;
Proof proof=proof(actor,before,resolution,Instant.now());
Link link=repository.latest(actor,id);
if(!before.equals(registration(actor,id,CatalogAction.VIEW,false)))throw AssetCatalogDomainException.conflict("登记已变化,请重新读取");
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_VIEW");
String state=associationState(before,link,proof,Instant.now());
return new Inspection(Long.toString(id),Long.toString(before.version()),before.assetRef(),resolution==null?"UNKNOWN":resolution.state().name(),state,
proof==null?null:new Candidate(Long.toString(proof.identity().assetId()),Long.toString(proof.identity().businessVersion()),proof.sha256(),proof.expiresAt()),view(link),Instant.now(),"TABLE".equals(before.type())?null:"当前已有身份来源只支持表;其他登记类型需先建立对应来源证明");
}
LinkView link(long id,String rawKey,Command command) {
validate(command);String key=policy.idempotencyKey(rawKey),path=path(id),hash=policy.requestHash(command);
Actor actor=actor("ASSET_CATALOG_IDENTITY_LINK");
Registration before=registration(actor,id,CatalogAction.MAINTAIN,false);
var completed=repository.receipt(actor,path,key);
if(completed!=null)return replay(actor,before,completed,hash);
if(canceled(repository.request(actor,path,key),cancellationHash(actor,id,key)))throw AssetCatalogDomainException.conflict("该请求已结束且未写入,请重新核验后使用新请求标识");
if(!"TABLE".equals(before.type()))throw AssetCatalogDomainException.conflict("登记类型与当前表身份来源不一致,请先核对登记类型");
Proof proof=proof(actor,before,resolve(before.assetRef()),Instant.now());
requireCandidate(command,proof);
return transactions.execute(status->{
Registration locked=registration(actor,id,CatalogAction.MAINTAIN,true);
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_LINK");
var ticket=catalogs.begin(actor,"POST",path,key,hash);
if(ticket.responseId()!=null)return replay(actor,locked,ticket,hash);
Link current=repository.latest(actor,id);
if(!before.equals(locked)||locked.version()!=command.registrationVersion()||(current==null?0:current.version())!=command.expectedLinkVersion())
throw AssetCatalogDomainException.conflict("登记或关联版本已变化,请重新核对");
if(!proof.expiresAt().isAfter(Instant.now()))throw AssetCatalogDomainException.conflict("身份核验证据已过期,请重新核对");
Link saved=repository.insert(actor,locked,command.expectedLinkVersion()+1,proof,mapper.writeValueAsString(proof.identity().sourceEvidence()),ticket.requestId());
catalogs.authorize(actor,locked.catalogId(),CatalogAction.MAINTAIN);
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_LINK");
catalogs.trajectory(actor,locked.catalogId(),"IDENTITY_LINK",null,null,ticket.requestId(),"登记 "+id+" 关联已有生命周期资产 "+saved.assetId()+",证据版本 "+saved.version());
catalogs.complete(actor,"POST",path,key,saved.id());
return view(saved);
});
}
Receipt request(long id,String rawKey) {
String key=policy.idempotencyKey(rawKey);Actor actor=actor("ASSET_CATALOG_IDENTITY_VIEW");
Registration registration=registration(actor,id,CatalogAction.VIEW,false);
Receipt result=requestReceipt(actor,registration,key,repository.request(actor,path(id),key));
registration(actor,id,CatalogAction.VIEW,false);
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_VIEW");
return result;
}
Receipt cancel(long id,String rawKey) {
String key=policy.idempotencyKey(rawKey);Actor actor=actor("ASSET_CATALOG_IDENTITY_LINK");
return transactions.execute(status->{
Registration locked=registration(actor,id,CatalogAction.MAINTAIN,true);
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_LINK");
var existing=repository.request(actor,path(id),key);
Receipt result;
if(existing!=null)result=requestReceipt(actor,locked,key,existing);
else {
// A durable failed request blocks an original write which arrives after cancellation.
var canceled=repository.cancelUnobserved(actor,path(id),key,cancellationHash(actor,id,key));
result=requestReceipt(actor,locked,key,canceled);
catalogs.trajectory(actor,locked.catalogId(),"IDENTITY_LINK_CANCEL",null,null,canceled.requestId(),"登记 "+id+" 的未提交身份关联请求已结束,未写入关联");
}
catalogs.authorize(actor,locked.catalogId(),CatalogAction.MAINTAIN);
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_LINK");
return result;
});
}
private Receipt requestReceipt(Actor actor,Registration registration,String key,Request request) {
String state="NOT_OBSERVED";Link link=null;
if(request!=null){
if("COMPLETED".equals(request.status())&&request.responseId()!=null){
link=repository.get(actor,request.responseId());
if(link.registrationId()!=registration.id()||!link.requestId().equals(request.requestId()))throw AssetCatalogDomainException.conflict("关联回执与登记不一致");
state="COMPLETED";
}else if(canceled(request,cancellationHash(actor,registration.id(),key)))state="CANCELED_NO_WRITE";
else state="PROCESSING".equals(request.status())?"PROCESSING":"UNKNOWN";
}
return new Receipt(state,Long.toString(registration.id()),key,view(link));
}
private String cancellationHash(Actor actor,long id,String key){return policy.requestHash(java.util.List.of("CATALOG_IDENTITY_LINK_CANCELED_NO_WRITE",actor.actorId(),actor.organizationId(),actor.departmentId(),id,key));}
private static boolean canceled(Request request,String hash){return request!=null&&"FAILED".equals(request.status())&&request.responseId()==null&&hash.equals(request.hash());}
private LinkView replay(Actor actor,Registration registration,AssetCatalogJdbcRepository.RequestTicket ticket,String hash) {
if(!Objects.equals(ticket.hash(),hash))throw AssetCatalogDomainException.conflict("同一Idempotency-Key载荷不一致");
Link link=repository.get(actor,ticket.responseId());
if(link.registrationId()!=registration.id())throw AssetCatalogDomainException.conflict("关联回执与登记不一致");
actors.requireCurrent(actor,"ASSET_CATALOG_IDENTITY_LINK");return view(link);
}
private Actor actor(String purpose){actors.require(purpose);Actor actor=actors.current();actors.requireCurrent(actor,purpose);return actor;}
private Registration registration(Actor actor,long id,CatalogAction action,boolean lock){if(id<=0)throw AssetCatalogDomainException.validation("登记ID无效");var row=repository.registration(actor,id,lock);catalogs.authorize(actor,row.catalogId(),action);return row;}
private AssetResolution resolve(String ref) {
if(ref==null||ref.isBlank()||ref.length()>512)return null;
try{return identities.resolve(new AssetIdentityModel.Lookup(null,null,ref));}
catch(AssetIdentityModel.Failure failure){if(failure.code()==ErrorCode.FORBIDDEN||failure.code()==ErrorCode.UNAUTHENTICATED)throw AssetCatalogDomainException.forbidden();throw failure;}
}
Proof proof(Actor actor,Registration registration,AssetResolution resolution,Instant now) {
if(!"TABLE".equals(registration.type())||resolution==null||resolution.state()!=MappingState.MAPPED||resolution.error()!=null||resolution.identity()==null)return null;
var identity=resolution.identity();
if(!identity.assetRef().equals(registration.assetRef())||identity.organizationId()!=actor.organizationId()||identity.departmentId()!=actor.departmentId()
||identity.sourceEvidence().isEmpty()||identity.sourceEvidence().stream().anyMatch(e->e.observedAt().isAfter(now)||!e.expiresAt().isAfter(now)))return null;
var evidence=identity.sourceEvidence().stream().sorted(Comparator.comparing(EvidenceRef::owner).thenComparing(EvidenceRef::reference).thenComparingLong(EvidenceRef::version))
.map(e->java.util.List.of(e.owner(),e.reference(),e.version(),e.sha256())).toList();
String sha=policy.requestHash(java.util.List.of(identity.assetId(),identity.assetRef(),identity.businessVersion(),identity.organizationId(),identity.departmentId(),identity.responsibilityRef(),identity.state(),identity.legacyDetailIds().stream().sorted().toList(),evidence));
return new Proof(identity,sha,identity.sourceEvidence().stream().map(EvidenceRef::expiresAt).min(Instant::compareTo).orElseThrow());
}
static String associationState(Registration registration,Link link,Proof proof,Instant now) {
if(link==null)return "UNLINKED";
if(!"TABLE".equals(registration.type())||link.registrationVersion()!=registration.version()||!link.assetRef().equals(registration.assetRef())||!link.expiresAt().isAfter(now))return "STALE";
if(proof==null||!proof.expiresAt().isAfter(now))return "UNKNOWN";
return link.assetId()==proof.identity().assetId()&&link.businessVersion()==proof.identity().businessVersion()&&link.evidenceSha256().equals(proof.sha256())?"CURRENT":"STALE";
}
static void requireCandidate(Command command,Proof proof){
if(proof==null||!command.assetId().equals(Long.toString(proof.identity().assetId()))||command.businessVersion()!=proof.identity().businessVersion()||!command.evidenceSha256().equals(proof.sha256()))
throw AssetCatalogDomainException.conflict("当前身份来源与已核对结果不一致,请重新核对后关联");
}
private static void validate(Command c){if(c==null||c.registrationVersion()==null||c.registrationVersion()<0||c.expectedLinkVersion()==null||c.expectedLinkVersion()<0||c.expectedLinkVersion()==Long.MAX_VALUE||c.businessVersion()==null||c.businessVersion()<0||c.assetId()==null||!c.assetId().matches("[1-9][0-9]{0,18}")||c.evidenceSha256()==null||!c.evidenceSha256().matches("[a-f0-9]{64}"))throw AssetCatalogDomainException.validation("关联请求或版本无效");}
private static LinkView view(Link link){return link==null?null:new LinkView(Long.toString(link.id()),Long.toString(link.registrationId()),Long.toString(link.version()),Long.toString(link.assetId()),Long.toString(link.businessVersion()),link.evidenceSha256(),link.expiresAt(),link.linkedAt(),link.requestId());}
private static String path(long id){return "/api/governance/v1/asset-catalogs/registrations/"+id+"/identity-link";}
}
@@ -0,0 +1,152 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogOverviewReader.Registration;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogIdentityLinkService.Inspection;
/** On-demand, bounded revalidation. Saved associations alone are never counted as current identities. */
@Component
@RequiredArgsConstructor
class AssetCatalogIdentitySummaryReader {
private static final String PURPOSE = "ASSET_CATALOG_VIEW";
private static final int MAX_SUPPORTED_REGISTRATIONS = 100;
private final AssetCatalogActorProvider actors;
private final AssetCatalogOverviewReader overview;
private final AssetCatalogIdentityLinkService identities;
private final AssetCatalogIdentityLinkRepository links;
private final AssetCatalogSourceIdentityService sourceIdentities;
record Summary(String scopeHash, Instant readAt, Instant expiresAt, String countKind,
int registrations, int tableRegistrations, int verifiedRegistrations,
int distinctIdentities, int duplicateRegistrations, int unlinked,
int stale, int unknown, int unsupported, int supportedRegistrations, List<TypeCoverage> types) { }
/** Null identity counts are deliberately different from a verified empty set. */
record TypeCoverage(String type, int registrations, int reliableRegistrations,
String verification, Integer verifiedRegistrations, Integer distinctIdentities) { }
private record Checked(Registration registration, Inspection inspection, AssetCatalogSourceIdentityService.Inspection source) { }
Summary read(Long catalogId) {
var actor = actors.current();
actors.requireCurrent(actor, PURPOSE);
var before = overview.registrations(catalogId);
long supportedCount = before.rows().stream().filter(row -> supported(row.type())).count();
if (supportedCount > MAX_SUPPORTED_REGISTRATIONS)
throw AssetCatalogDomainException.conflict("当前范围超过 100 条可核验登记,请选择较小目录后核验身份数");
var checked = new ArrayList<Checked>();
long deadline = System.nanoTime() + java.time.Duration.ofSeconds(15).toNanos();
for (var row : before.rows()) {
Inspection inspection = null;
AssetCatalogSourceIdentityService.Inspection source = null;
if ("TABLE".equals(row.type()) && row.reliable() && System.nanoTime() < deadline) {
try { inspection = identities.inspect(Long.parseLong(row.registrationId())); }
catch (AssetCatalogDomainException rejected) { throw rejected; }
catch (RuntimeException unavailable) { /* Unavailable owners count as unknown. */ }
}
if (AssetCatalogSourceIdentityService.supported(row.type()) && row.reliable() && System.nanoTime() < deadline) {
try { source = sourceIdentities.inspect(Long.parseLong(row.registrationId())); }
catch (AssetCatalogDomainException rejected) { throw rejected; }
catch (RuntimeException unavailable) { /* No current source observation. */ }
}
checked.add(new Checked(row, inspection, source));
}
var after = overview.registrations(catalogId);
if (!before.scopeHash().equals(after.scopeHash()) || !before.rows().equals(after.rows())
|| !before.catalogs().equals(after.catalogs()))
throw AssetCatalogDomainException.conflict("核验期间目录或登记已变化,请重新读取");
// A newer saved association must not be replaced by an earlier CURRENT observation.
for (int index = 0; index < checked.size(); index++) {
var item = checked.get(index);
var inspection = item.inspection();
if (inspection != null && "CURRENT".equals(inspection.associationState())) {
var latest = links.latest(actor, Long.parseLong(item.registration().registrationId()));
if (latest == null || inspection.link() == null
|| !Long.toString(latest.id()).equals(inspection.link().linkId())
|| !Long.toString(latest.version()).equals(inspection.link().version()))
checked.set(index, new Checked(item.registration(), null, null));
}
if (item.source() != null && "CURRENT".equals(item.source().associationState())
&& !sourceIdentities.stillCurrent(actor,Long.parseLong(item.registration().registrationId()),item.source().link()))
checked.set(index,new Checked(item.registration(),null,null));
}
// Recheck each contributing type after the complete range read, including live permission revocation.
for(String type:checked.stream().filter(item->item.inspection()!=null||item.source()!=null).map(item->item.registration().type()).distinct().toList())
actors.requireCurrent(actor,"TABLE".equals(type)?"ASSET_CATALOG_IDENTITY_VIEW":AssetCatalogSourceIdentityService.purpose(type,false));
actors.requireCurrent(actor, PURPOSE);
return summarize(before.scopeHash(), checked, Instant.now());
}
private static Summary summarize(String scope, List<Checked> rows, Instant now) {
int tables = 0, supported = 0, verified = 0, unlinked = 0, stale = 0, unknown = 0, unsupported = 0;
Instant expires = null;
Set<String> ids = new HashSet<>();
java.util.Map<String,Integer> verifiedByType = new java.util.HashMap<>();
java.util.Map<String,Set<String>> idsByType = new java.util.HashMap<>();
for (var item : rows) {
String type=item.registration().type();
if (!supported(type)) { unsupported++; continue; }
supported++;
if(AssetCatalogSourceIdentityService.supported(type)) {
var source=item.source();
if(source==null||!item.registration().registrationId().equals(source.registrationId())
||!Long.toString(item.registration().version()).equals(source.registrationVersion())) { unknown++; continue; }
switch(source.associationState()) {
case "CURRENT" -> {
var proof=source.current();var link=source.link();
if(proof==null||link==null||!proof.expiresAt().isAfter(now)||!type.equals(proof.type())
||!cn.aixunkeji.datagov.dataproduct.api.catalogidentity.CatalogIdentityOwner.owner(type).equals(proof.owner())
||!type.equals(link.type())||!proof.owner().equals(link.owner())||!proof.source().sourceRef().equals(link.sourceRef())
||!proof.source().sourceVersion().equals(link.sourceVersion())||!proof.evidenceSha256().equals(link.evidenceSha256())) {unknown++;break;}
String identity=type+":"+proof.owner()+":"+proof.source().sourceRef();verified++;ids.add(identity);
verifiedByType.merge(type,1,Integer::sum);idsByType.computeIfAbsent(type,k->new HashSet<>()).add(identity);
if(expires==null||proof.expiresAt().isBefore(expires))expires=proof.expiresAt();
}
case "UNLINKED" -> unlinked++;
case "STALE" -> stale++;
default -> unknown++;
}
continue;
}
tables++;
var value = item.inspection();
if (value == null || !item.registration().registrationId().equals(value.registrationId())
|| !Long.toString(item.registration().version()).equals(value.registrationVersion())) { unknown++; continue; }
switch (value.associationState()) {
case "CURRENT" -> {
if (value.link() == null || value.candidate() == null || !value.link().expiresAt().isAfter(now)
|| !value.candidate().expiresAt().isAfter(now)
|| !value.link().assetId().equals(value.candidate().assetId())) { unknown++; break; }
verified++;
String identity="TABLE:LIFECYCLE:"+value.link().assetId();ids.add(identity);
verifiedByType.merge(type,1,Integer::sum);idsByType.computeIfAbsent(type,k->new HashSet<>()).add(identity);
Instant validUntil = value.link().expiresAt().isBefore(value.candidate().expiresAt())
? value.link().expiresAt() : value.candidate().expiresAt();
if (expires == null || validUntil.isBefore(expires)) expires = validUntil;
}
case "UNLINKED" -> unlinked++;
case "STALE" -> stale++;
default -> unknown++;
}
}
var kinds = new ArrayList<>(List.of("TABLE", "DATASET", "FILE", "REPORT", "API", "MODEL"));
if (rows.stream().anyMatch(item -> !kinds.contains(item.registration().type()))) kinds.add("UNKNOWN");
var coverage = new ArrayList<TypeCoverage>();
for (String kind : kinds) {
var selected = rows.stream().filter(item -> kind.equals(item.registration().type())
|| "UNKNOWN".equals(kind) && !List.of("TABLE", "DATASET", "FILE", "REPORT", "API", "MODEL")
.contains(item.registration().type())).toList();
boolean available = supported(kind);
coverage.add(new TypeCoverage(kind, selected.size(), (int) selected.stream()
.filter(item -> item.registration().reliable()).count(), available ? "SUPPORTED" : "NOT_CONNECTED",
available ? verifiedByType.getOrDefault(kind,0) : null, available ? idsByType.getOrDefault(kind,Set.of()).size() : null));
}
return new Summary(scope, now, expires, "DISTINCT_CURRENT_TYPED_SOURCE_IDENTITY", rows.size(), tables,
verified, ids.size(), verified - ids.size(), unlinked, stale, unknown, unsupported, supported, List.copyOf(coverage));
}
private static boolean supported(String type){return "TABLE".equals(type)||AssetCatalogSourceIdentityService.supported(type);}
}
@@ -0,0 +1,68 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
/** Read-only bridge from the immutable inventory evidence to the existing catalog command. */
@Repository
@RequiredArgsConstructor
class AssetCatalogInventorySource {
private final JdbcTemplate jdbc;
Source read(long taskId, long candidateId, AssetCatalogActorProvider.Actor actor) {
return jdbc.query("""
SELECT c.external_id,c.asset_fqn,c.resource_type,c.payload_sha256 AS candidate_sha,
c.confirmed_flag,c.version AS candidate_version,t.task_status,
s.snapshot_id,s.observed_at,s.reliable_flag,s.payload_sha256 AS snapshot_sha,
x.confirmation_id,x.valid_flag,x.in_scope_flag,x.confirmed_definition,x.confirmed_owner_user_id
FROM asset_inventory_candidate c
JOIN asset_inventory_task t ON t.task_id=c.task_id
AND t.organization_id=c.organization_id AND t.department_id=c.department_id AND t.del_flag='0'
JOIN asset_inventory_source_snapshot s ON s.snapshot_id=c.snapshot_id AND s.task_id=c.task_id
AND s.organization_id=c.organization_id AND s.department_id=c.department_id AND s.del_flag='0'
JOIN asset_inventory_confirmation x ON x.candidate_id=c.candidate_id AND x.task_id=c.task_id
AND x.organization_id=c.organization_id AND x.department_id=c.department_id AND x.del_flag='0'
WHERE c.task_id=? AND c.candidate_id=? AND c.organization_id=? AND c.department_id=? AND c.del_flag='0'
ORDER BY x.confirmation_id DESC LIMIT 1
""", (rs, row) -> new Source(rs.getString("external_id"), rs.getString("asset_fqn"),
rs.getString("resource_type"), rs.getString("candidate_sha"), "1".equals(rs.getString("confirmed_flag")),
rs.getLong("candidate_version"), rs.getString("task_status"), rs.getLong("snapshot_id"),
rs.getTimestamp("observed_at") == null ? null : rs.getTimestamp("observed_at").toLocalDateTime(),
"1".equals(rs.getString("reliable_flag")), rs.getString("snapshot_sha"), rs.getLong("confirmation_id"),
"1".equals(rs.getString("valid_flag")), "1".equals(rs.getString("in_scope_flag")),
rs.getString("confirmed_definition"), rs.getString("confirmed_owner_user_id")),
taskId, candidateId, actor.organizationId(), actor.departmentId()).stream().findFirst()
.orElseThrow(() -> AssetCatalogDomainException.conflict("盘点候选或确认来源不存在或不在当前组织部门范围内"));
}
record Source(String externalId, String fqn, String resourceType, String candidateSha, boolean confirmed,
long candidateVersion, String taskStatus, long snapshotId, LocalDateTime observedAt,
boolean reliable, String snapshotSha, long confirmationId, boolean valid, boolean inScope,
String definition, String ownerRef) {
AssetCatalogApi.CatalogAssetCommand command(AssetCatalogApi.InventoryCatalogCommand request) {
if (!"COMPLETED".equals(taskStatus) || !confirmed || !valid || !inScope) {
throw AssetCatalogDomainException.conflict("仅已完成盘点中的有效纳管确认资产可编目");
}
if (candidateVersion != request.candidateVersion()) {
throw AssetCatalogDomainException.conflict("盘点候选版本已变化,请刷新后重试");
}
if (snapshotSha == null || !snapshotSha.equals(candidateSha)) {
throw AssetCatalogDomainException.conflict("盘点候选与来源快照SHA不一致");
}
AssetCatalogApi.AssetType type;
try { type = AssetCatalogApi.AssetType.valueOf(resourceType); }
catch (IllegalArgumentException | NullPointerException exception) {
throw AssetCatalogDomainException.validation("盘点资产类型无效");
}
return new AssetCatalogApi.CatalogAssetCommand(externalId, fqn, type,
fqn == null ? null : fqn.substring(fqn.lastIndexOf('.') + 1), definition, java.util.List.of(),
"USER", ownerRef, "ASSET_INVENTORY",
"inventory:" + request.taskId() + ":candidate:" + request.candidateId()
+ ":snapshot:" + snapshotId + ":confirmation:" + confirmationId,
observedAt, reliable, snapshotSha, request.version());
}
}
}
@@ -0,0 +1,151 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import tools.jackson.core.JacksonException;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.json.JsonMapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
@Repository
@RequiredArgsConstructor
class AssetCatalogJdbcRepository {
private static final String NODE_COLUMNS = "catalog_id,catalog_code,catalog_name,parent_id,description,sort_order,catalog_status,organization_id,department_id,version,create_time,update_time";
private final JdbcTemplate jdbc;
private final JsonMapper mapper;
List<NodeView> tree(AssetCatalogActorProvider.Actor actor, CatalogAction action) {
if (actor.administrator()) return jdbc.query("SELECT " + NODE_COLUMNS + " FROM asset_catalog_node WHERE organization_id=? AND department_id=? AND del_flag='0' ORDER BY parent_id,sort_order,catalog_id", this::mapNode, actor.organizationId(), actor.departmentId());
String sql = "WITH RECURSIVE allowed(catalog_id,include_descendants) AS ("
+ "SELECT p.catalog_id,p.include_descendants FROM asset_catalog_permission p WHERE p.del_flag='0' "
+ "AND JSON_CONTAINS(?,JSON_QUOTE(CONCAT(p.subject_type,':',p.subject_ref))) "
+ "AND JSON_CONTAINS(p.actions_json,JSON_QUOTE(?)) AND p.effective_from<=NOW() AND (p.effective_to IS NULL OR p.effective_to>NOW()) "
+ "UNION ALL SELECT n.catalog_id,'1' FROM asset_catalog_node n JOIN allowed a ON n.parent_id=a.catalog_id "
+ "WHERE a.include_descendants='1' AND n.del_flag='0') SELECT DISTINCT n." + NODE_COLUMNS.replace(",", ",n.")
+ " FROM asset_catalog_node n JOIN allowed a ON a.catalog_id=n.catalog_id WHERE n.organization_id=? AND n.department_id=? AND n.del_flag='0' ORDER BY n.parent_id,n.sort_order,n.catalog_id";
return jdbc.query(sql, this::mapNode, write(actor.subjectRefs()), action.name(),
actor.organizationId(), actor.departmentId());
}
void authorize(AssetCatalogActorProvider.Actor actor, long catalogId, CatalogAction action) {
if (actor.administrator()) { node(catalogId, actor); return; }
String sql = "WITH RECURSIVE ancestors(catalog_id,parent_id) AS (SELECT catalog_id,parent_id FROM asset_catalog_node WHERE catalog_id=? AND organization_id=? AND department_id=? AND del_flag='0' UNION ALL SELECT n.catalog_id,n.parent_id FROM asset_catalog_node n JOIN ancestors a ON n.catalog_id=a.parent_id WHERE n.del_flag='0') SELECT COUNT(*) FROM ancestors a JOIN asset_catalog_permission p ON p.catalog_id=a.catalog_id AND p.del_flag='0' WHERE JSON_CONTAINS(?,JSON_QUOTE(CONCAT(p.subject_type,':',p.subject_ref))) AND JSON_CONTAINS(p.actions_json,JSON_QUOTE(?)) AND (a.catalog_id=? OR p.include_descendants='1') AND p.effective_from<=NOW() AND (p.effective_to IS NULL OR p.effective_to>NOW())";
Long count = jdbc.queryForObject(sql, Long.class, catalogId, actor.organizationId(),
actor.departmentId(), write(actor.subjectRefs()), action.name(), catalogId);
if (count == null || count == 0) throw AssetCatalogDomainException.forbidden();
}
NodeView node(long id, AssetCatalogActorProvider.Actor actor) {
return jdbc.query("SELECT " + NODE_COLUMNS + " FROM asset_catalog_node WHERE catalog_id=? AND organization_id=? AND department_id=? AND del_flag='0'", this::mapNode, id, actor.organizationId(), actor.departmentId()).stream().findFirst().orElseThrow(AssetCatalogDomainException::notFound);
}
DetailView detail(long id, AssetCatalogActorProvider.Actor actor) {
List<PermissionView> visiblePermissions = canAccess(actor, id, CatalogAction.PERMISSION)
? permissions(id) : List.of();
return new DetailView(node(id, actor), assets(id, actor), publications(id),
visiblePermissions, trajectories(id));
}
long create(AssetCatalogActorProvider.Actor actor, CreateNodeCommand command) {
if (command.parentId() != null) { node(command.parentId(), actor); if (depth(command.parentId()) >= AssetCatalogPolicy.MAX_DEPTH) throw AssetCatalogDomainException.conflict("目录深度超过上限"); }
long id = IdGeneratorUtil.nextLongId();
try { jdbc.update("INSERT INTO asset_catalog_node(catalog_id,catalog_code,catalog_name,parent_id,description,sort_order,catalog_status,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,'DRAFT',?,?,?,?,NOW(),?,NOW(),'0',0)", id, command.catalogCode(), command.catalogName(), command.parentId(), command.description(), command.sortOrder(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId()); }
catch (DuplicateKeyException e) { throw AssetCatalogDomainException.conflict("同一组织范围目录编码已存在"); }
return id;
}
void update(AssetCatalogActorProvider.Actor actor, long id, UpdateNodeCommand command) {
required(jdbc.update("UPDATE asset_catalog_node SET catalog_name=?,description=?,sort_order=?,update_by=?,update_time=NOW(),version=version+1 WHERE catalog_id=? AND organization_id=? AND department_id=? AND catalog_status IN ('DRAFT','UNPUBLISHED') AND version=? AND del_flag='0'", command.catalogName(), command.description(), command.sortOrder(), actor.actorId(), id, actor.organizationId(), actor.departmentId(), command.version()), "目录版本已变化或当前状态不可调整");
}
boolean eligibleParent(AssetCatalogActorProvider.Actor actor,Long objectId,long parentId){
if(objectId!=null&&objectId==parentId||!canAccess(actor,parentId,CatalogAction.MAINTAIN))return false;
record Ancestor(long id,Long parent,int depth) { }
var ancestors=jdbc.query("WITH RECURSIVE a AS (SELECT catalog_id,parent_id,1 depth FROM asset_catalog_node WHERE catalog_id=? AND organization_id=? AND department_id=? AND del_flag='0' UNION ALL SELECT n.catalog_id,n.parent_id,a.depth+1 FROM asset_catalog_node n JOIN a ON n.catalog_id=a.parent_id WHERE n.organization_id=? AND n.department_id=? AND n.del_flag='0' AND a.depth<=?) SELECT catalog_id,parent_id,depth FROM a",(r,n)->new Ancestor(r.getLong(1),r.getObject(2,Long.class),r.getInt(3)),parentId,actor.organizationId(),actor.departmentId(),actor.organizationId(),actor.departmentId(),AssetCatalogPolicy.MAX_DEPTH);
if(ancestors.isEmpty()||ancestors.stream().noneMatch(a->a.parent()==null)||ancestors.stream().anyMatch(a->a.depth()>AssetCatalogPolicy.MAX_DEPTH||objectId!=null&&a.id()==objectId))return false;
int depth=ancestors.stream().mapToInt(Ancestor::depth).max().orElse(0);int height=1;
if(objectId!=null){node(objectId,actor);Integer value=jdbc.queryForObject("WITH RECURSIVE d AS (SELECT catalog_id,1 depth FROM asset_catalog_node WHERE catalog_id=? AND organization_id=? AND department_id=? AND del_flag='0' UNION ALL SELECT n.catalog_id,d.depth+1 FROM asset_catalog_node n JOIN d ON n.parent_id=d.catalog_id WHERE n.organization_id=? AND n.department_id=? AND n.del_flag='0' AND d.depth<=?) SELECT COALESCE(MAX(depth),1) FROM d",Integer.class,objectId,actor.organizationId(),actor.departmentId(),actor.organizationId(),actor.departmentId(),AssetCatalogPolicy.MAX_DEPTH);if(value==null)return false;height=value;}
return depth+height<=AssetCatalogPolicy.MAX_DEPTH;
}
void move(AssetCatalogActorProvider.Actor actor, long id, MoveNodeCommand command) {
if (command.parentId() != null && command.parentId() == id) throw AssetCatalogDomainException.conflict("目录不能以自身为父节点");
if (command.parentId() != null) {
node(command.parentId(), actor);
Long cycle = jdbc.queryForObject("WITH RECURSIVE descendants AS (SELECT catalog_id FROM asset_catalog_node WHERE parent_id=? AND del_flag='0' UNION ALL SELECT n.catalog_id FROM asset_catalog_node n JOIN descendants d ON n.parent_id=d.catalog_id WHERE n.del_flag='0') SELECT COUNT(*) FROM descendants WHERE catalog_id=?", Long.class, id, command.parentId());
if (cycle != null && cycle > 0) throw AssetCatalogDomainException.conflict("目录移动会形成环");
if (depth(command.parentId()) + subtreeDepth(id) > AssetCatalogPolicy.MAX_DEPTH) throw AssetCatalogDomainException.conflict("移动后目录子树深度超过上限");
}
required(jdbc.update("UPDATE asset_catalog_node SET parent_id=?,sort_order=?,update_by=?,update_time=NOW(),version=version+1 WHERE catalog_id=? AND organization_id=? AND department_id=? AND catalog_status IN ('DRAFT','UNPUBLISHED') AND version=? AND del_flag='0'", command.parentId(), command.sortOrder(), actor.actorId(), id, actor.organizationId(), actor.departmentId(), command.version()), "目录版本已变化或当前状态不可调整");
}
void catalog(AssetCatalogActorProvider.Actor actor, long id, CatalogAssetCommand command) {
required(jdbc.update("UPDATE asset_catalog_node SET update_by=?,update_time=NOW(),version=version+1 WHERE catalog_id=? AND organization_id=? AND department_id=? AND catalog_status IN ('DRAFT','UNPUBLISHED') AND version=? AND del_flag='0'", actor.actorId(), id, actor.organizationId(), actor.departmentId(), command.version()), "目录版本已变化或当前状态不可编目");
try { jdbc.update("INSERT INTO asset_catalog_item(catalog_asset_id,catalog_id,asset_ref,asset_fqn,asset_type,asset_name,description,tags_json,owner_type,owner_ref,source_type,source_ref,observed_at,reliable_flag,payload_sha256,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,'1',?,?,?,?,?,NOW(),?,NOW(),'0',0)", IdGeneratorUtil.nextLongId(), id, command.assetRef(), command.assetFqn(), command.assetType().name(), command.assetName(), command.description(), write(command.tags()), command.ownerType(), command.ownerRef(), command.sourceType(), command.sourceRef(), command.observedAt(), command.payloadSha256(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId()); }
catch (DuplicateKeyException e) { throw AssetCatalogDomainException.conflict("资产已在该目录编目"); }
}
PublicationView publish(AssetCatalogActorProvider.Actor actor, long id, PublishCommand command, String snapshotSha, List<AssetView> assets) {
required(jdbc.update("UPDATE asset_catalog_node SET catalog_status='PUBLISHED',update_by=?,update_time=NOW(),version=version+1 WHERE catalog_id=? AND organization_id=? AND department_id=? AND catalog_status IN ('DRAFT','UNPUBLISHED') AND version=? AND del_flag='0'", actor.actorId(), id, actor.organizationId(), actor.departmentId(), command.version()), "目录版本已变化或状态不可发布");
Long max = jdbc.queryForObject("SELECT COALESCE(MAX(publication_version),0) FROM asset_catalog_publication WHERE catalog_id=?", Long.class, id);
long publicationId = IdGeneratorUtil.nextLongId(); long publicationVersion = (max == null ? 0 : max) + 1;
jdbc.update("INSERT INTO asset_catalog_publication(publication_id,catalog_id,publication_version,snapshot_sha256,item_count,publish_reason,actor_id,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)", publicationId, id, publicationVersion, snapshotSha, assets.size(), command.reason(), actor.actorId(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
for (AssetView asset : assets) jdbc.update("INSERT INTO asset_catalog_publication_item(publication_item_id,publication_id,catalog_asset_id,asset_ref,asset_fqn,asset_type,asset_name,description,tags_json,owner_type,owner_ref,source_type,source_ref,observed_at,payload_sha256,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())", IdGeneratorUtil.nextLongId(), publicationId, asset.catalogAssetId(), asset.assetRef(), asset.assetFqn(), asset.assetType().name(), asset.assetName(), asset.description(), write(asset.tags()), asset.ownerType(), asset.ownerRef(), asset.sourceType(), asset.sourceRef(), asset.observedAt(), asset.payloadSha256());
return publication(publicationId);
}
PermissionView permission(AssetCatalogActorProvider.Actor actor, long id, PermissionCommand command) {
node(id, actor); long permissionId = IdGeneratorUtil.nextLongId();
jdbc.update("INSERT INTO asset_catalog_permission(permission_id,catalog_id,subject_type,subject_ref,actions_json,include_descendants,effective_from,effective_to,grant_reason,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)", permissionId, id, command.subjectType().name(), command.subjectRef(), write(command.actions()), command.includeDescendants() ? "1" : "0", command.effectiveFrom(), command.effectiveTo(), command.reason(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
return permission(permissionId);
}
void status(AssetCatalogActorProvider.Actor actor, long id, CatalogStatus current, StatusCommand command) {
required(jdbc.update("UPDATE asset_catalog_node SET catalog_status=?,update_by=?,update_time=NOW(),version=version+1 WHERE catalog_id=? AND organization_id=? AND department_id=? AND catalog_status=? AND version=? AND del_flag='0'", command.targetStatus().name(), actor.actorId(), id, actor.organizationId(), actor.departmentId(), current.name(), command.version()), "目录状态或版本已变化");
}
List<AssetView> assets(long id, AssetCatalogActorProvider.Actor actor) { node(id, actor); return jdbc.query("SELECT catalog_asset_id,catalog_id,asset_ref,asset_fqn,asset_type,asset_name,description,tags_json,owner_type,owner_ref,source_type,source_ref,observed_at,reliable_flag,payload_sha256,version,create_time FROM asset_catalog_item WHERE catalog_id=? AND organization_id=? AND department_id=? AND del_flag='0' ORDER BY catalog_asset_id", this::mapAsset, id, actor.organizationId(), actor.departmentId()); }
List<PublicationView> publications(long id) { return jdbc.query("SELECT publication_id,catalog_id,publication_version,snapshot_sha256,item_count,publish_reason,actor_id,create_time FROM asset_catalog_publication WHERE catalog_id=? AND del_flag='0' ORDER BY publication_version DESC", this::mapPublication, id); }
PublicationView publication(long id) { return jdbc.query("SELECT publication_id,catalog_id,publication_version,snapshot_sha256,item_count,publish_reason,actor_id,create_time FROM asset_catalog_publication WHERE publication_id=? AND del_flag='0'", this::mapPublication, id).stream().findFirst().orElseThrow(AssetCatalogDomainException::notFound); }
List<PermissionView> permissions(long id) { return jdbc.query("SELECT permission_id,catalog_id,subject_type,subject_ref,actions_json,include_descendants,effective_from,effective_to,version,create_time FROM asset_catalog_permission WHERE catalog_id=? AND del_flag='0' ORDER BY permission_id", this::mapPermission, id); }
PermissionView permission(long id) { return jdbc.query("SELECT permission_id,catalog_id,subject_type,subject_ref,actions_json,include_descendants,effective_from,effective_to,version,create_time FROM asset_catalog_permission WHERE permission_id=? AND del_flag='0'", this::mapPermission, id).stream().findFirst().orElseThrow(AssetCatalogDomainException::notFound); }
List<TrajectoryView> trajectories(long id) { return jdbc.query("SELECT trajectory_id,catalog_id,action_type,before_status,after_status,request_id,actor_id,summary,create_time FROM asset_catalog_trajectory WHERE catalog_id=? ORDER BY trajectory_id", (rs,row) -> new TrajectoryView(rs.getLong(1),rs.getLong(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getLong(7),rs.getString(8),rs.getTimestamp(9).toLocalDateTime()), id); }
void trajectory(AssetCatalogActorProvider.Actor actor, long id, String action, String before, String after, String requestId, String summary) { jdbc.update("INSERT INTO asset_catalog_trajectory(trajectory_id,catalog_id,action_type,before_status,after_status,request_id,actor_id,summary,organization_id,department_id,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,NOW())", IdGeneratorUtil.nextLongId(), id, action, before, after, requestId, actor.actorId(), summary, actor.organizationId(), actor.departmentId()); }
Long completedWorkflowRequest(AssetCatalogActorProvider.Actor actor, String path, String key) {
return jdbc.query("SELECT response_id FROM asset_catalog_request WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method='POST' AND request_path=? AND idempotency_key=? AND request_status='COMPLETED' AND response_id IS NOT NULL",
(rs, row) -> rs.getLong(1), actor.actorId(), actor.organizationId(), actor.departmentId(), path, key)
.stream().findFirst().orElse(null);
}
RequestTicket begin(AssetCatalogActorProvider.Actor actor, String method, String path, String key, String hash) {
List<RequestTicket> found = jdbc.query("SELECT request_id,request_sha256,response_id FROM asset_catalog_request WHERE actor_id=? AND request_method=? AND request_path=? AND idempotency_key=?", (rs,row) -> new RequestTicket(rs.getString(1),rs.getString(2),rs.getObject(3,Long.class)), actor.actorId(), method, path, key);
if (!found.isEmpty()) {
RequestTicket ticket = found.getFirst();
if (!ticket.hash().equals(hash)) throw AssetCatalogDomainException.conflict("同一Idempotency-Key载荷不一致");
if (ticket.responseId() == null) throw AssetCatalogDomainException.conflict("同一幂等请求正在处理或已失败");
return ticket;
}
String requestId = "ACR-" + IdGeneratorUtil.nextLongId();
jdbc.update("INSERT INTO asset_catalog_request(request_record_id,request_id,actor_id,request_method,request_path,idempotency_key,request_sha256,request_status,organization_id,department_id,create_time) VALUES(?,?,?,?,?,?,?,'PROCESSING',?,?,NOW())", IdGeneratorUtil.nextLongId(), requestId, actor.actorId(), method, path, key, hash, actor.organizationId(), actor.departmentId());
return new RequestTicket(requestId, hash, null);
}
void complete(AssetCatalogActorProvider.Actor actor, String method, String path, String key, long responseId) { required(jdbc.update("UPDATE asset_catalog_request SET request_status='COMPLETED',response_id=?,update_time=NOW(),version=version+1 WHERE actor_id=? AND request_method=? AND request_path=? AND idempotency_key=? AND request_status='PROCESSING'", responseId, actor.actorId(), method, path, key), "幂等请求状态已变化"); }
void fail(AssetCatalogActorProvider.Actor actor, String method, String path, String key) {
jdbc.update("UPDATE asset_catalog_request SET request_status='FAILED',update_time=NOW(),version=version+1 WHERE actor_id=? AND request_method=? AND request_path=? AND idempotency_key=? AND request_status='PROCESSING'",
actor.actorId(), method, path, key);
}
private int depth(long id) { Long depth = jdbc.queryForObject("WITH RECURSIVE ancestors AS (SELECT catalog_id,parent_id,1 depth FROM asset_catalog_node WHERE catalog_id=? AND del_flag='0' UNION ALL SELECT n.catalog_id,n.parent_id,a.depth+1 FROM asset_catalog_node n JOIN ancestors a ON n.catalog_id=a.parent_id WHERE n.del_flag='0') SELECT COALESCE(MAX(depth),0) FROM ancestors", Long.class, id); return depth == null ? 0 : depth.intValue(); }
private int subtreeDepth(long id) { Long depth = jdbc.queryForObject("WITH RECURSIVE descendants AS (SELECT catalog_id,1 depth FROM asset_catalog_node WHERE catalog_id=? AND del_flag='0' UNION ALL SELECT n.catalog_id,d.depth+1 FROM asset_catalog_node n JOIN descendants d ON n.parent_id=d.catalog_id WHERE n.del_flag='0') SELECT COALESCE(MAX(depth),1) FROM descendants", Long.class, id); return depth == null ? 1 : depth.intValue(); }
private boolean canAccess(AssetCatalogActorProvider.Actor actor, long id, CatalogAction action) {
if (actor.administrator()) return true;
try { authorize(actor, id, action); return true; }
catch (AssetCatalogDomainException exception) {
if (exception.status() == org.springframework.http.HttpStatus.FORBIDDEN) return false;
throw exception;
}
}
private NodeView mapNode(ResultSet rs, int row) throws SQLException { return new NodeView(rs.getLong(1),rs.getString(2),rs.getString(3),rs.getObject(4,Long.class),rs.getString(5),rs.getInt(6),CatalogStatus.valueOf(rs.getString(7)),rs.getLong(8),rs.getLong(9),rs.getLong(10),rs.getTimestamp(11).toLocalDateTime(),rs.getTimestamp(12).toLocalDateTime()); }
private AssetView mapAsset(ResultSet rs, int row) throws SQLException { return new AssetView(rs.getLong(1),rs.getLong(2),rs.getString(3),rs.getString(4),AssetType.valueOf(rs.getString(5)),rs.getString(6),rs.getString(7),readList(rs.getString(8),new TypeReference<List<String>>(){}),rs.getString(9),rs.getString(10),rs.getString(11),rs.getString(12),rs.getTimestamp(13).toLocalDateTime(),"1".equals(rs.getString(14)),rs.getString(15),rs.getLong(16),rs.getTimestamp(17).toLocalDateTime()); }
private PublicationView mapPublication(ResultSet rs, int row) throws SQLException { return new PublicationView(rs.getLong(1),rs.getLong(2),rs.getLong(3),rs.getString(4),rs.getInt(5),rs.getString(6),rs.getLong(7),rs.getTimestamp(8).toLocalDateTime()); }
private PermissionView mapPermission(ResultSet rs, int row) throws SQLException { return new PermissionView(rs.getLong(1),rs.getLong(2),SubjectType.valueOf(rs.getString(3)),rs.getString(4),readList(rs.getString(5),new TypeReference<List<CatalogAction>>(){}),rs.getBoolean(6),rs.getTimestamp(7).toLocalDateTime(),rs.getTimestamp(8)==null?null:rs.getTimestamp(8).toLocalDateTime(),rs.getLong(9),rs.getTimestamp(10).toLocalDateTime()); }
private String write(Object value) { try { return mapper.writeValueAsString(value); } catch (JacksonException e) { throw new IllegalStateException("资产目录JSON序列化失败", e); } }
private <T> T readList(String value, TypeReference<T> type) { try { return mapper.readValue(value,type); } catch (JacksonException e) { throw new IllegalStateException("资产目录JSON存储格式无效", e); } }
private static void required(int changed, String message) { if (changed != 1) throw AssetCatalogDomainException.conflict(message); }
record RequestTicket(String requestId, String hash, Long responseId) { }
}
@@ -0,0 +1,250 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.HexFormat;
import java.util.List;
import java.util.Set;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.CatalogAction;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogActorProvider.Actor;
/** Aggregate-only projection of the same directory scope used by the catalog owner. */
@Component
public final class AssetCatalogOverviewReader {
static final int MAX_VISIBLE_CATALOGS = 1_000;
private static final String PURPOSE = "ASSET_CATALOG_VIEW";
private final AssetCatalogActorProvider actors;
private final AssetCatalogJdbcRepository repository;
private final JdbcTemplate jdbc;
public AssetCatalogOverviewReader(AssetCatalogActorProvider actors,
AssetCatalogJdbcRepository repository, JdbcTemplate jdbc) {
this.actors = actors;
this.repository = repository;
this.jdbc = jdbc;
}
public record Observation(long actorId, long organizationId, long departmentId, long count,
LocalDateTime observedAt, String scopeSha256) { }
public record TypeCount(String type, long reliable, long uncertain) { }
public record CatalogGroup(String catalogId, String name, String status, List<TypeCount> types) { }
public record Portfolio(String scopeHash, java.time.Instant readAt, LocalDateTime lastRegistrationUpdate,
String countKind, boolean truncated, List<CatalogGroup> groups) { }
public record Registration(String registrationId, String catalogId, String assetRef, String name,
String type, boolean reliable, long version) { }
public record Registrations(String scopeHash, java.time.Instant readAt, List<CatalogGroup> catalogs,
List<Registration> rows) { }
/** Exact references are investigation clues, not evidence of a shared canonical identity. */
public Registrations registrations(Long catalogId) {
try {
Actor actor = actors.current();
actors.requireCurrent(actor, PURPOSE);
var before = visible(actor);
var selected = catalogId == null ? before : before.stream().filter(c -> c.id() == catalogId).toList();
if (catalogId != null && selected.isEmpty()) throw AssetCatalogDomainException.forbidden();
var first = registrationRows(actor, selected);
var second = registrationRows(actor, selected);
var after = visible(actor);
actors.requireCurrent(actor, PURPOSE);
if (!before.equals(after) || !first.equals(second))
throw AssetCatalogDomainException.conflict("目录范围或登记已变化,请重新读取");
return new Registrations(scopeSha(actor, selected), java.time.Instant.now(), selected.stream()
.map(c -> new CatalogGroup(Long.toString(c.id()), c.name(), c.status(), List.of())).toList(), second);
} catch (AssetCatalogDomainException rejected) {
throw rejected;
} catch (RuntimeException unavailable) {
throw AssetCatalogDomainException.conflict("资产登记线索暂不可用");
}
}
private List<Registration> registrationRows(Actor actor, List<CatalogRevision> catalogs) {
if (catalogs.isEmpty()) return List.of();
var args = new ArrayList<Object>(List.of(actor.organizationId(), actor.departmentId()));
catalogs.forEach(c -> args.add(c.id()));
Set<Long> ids = new HashSet<>();
var rows = jdbc.query("SELECT catalog_asset_id,catalog_id,asset_ref,asset_name,asset_type,reliable_flag,version "
+ "FROM asset_catalog_item WHERE organization_id=? AND department_id=? AND del_flag='0' AND catalog_id IN ("
+ String.join(",", java.util.Collections.nCopies(catalogs.size(), "?"))
+ ") ORDER BY catalog_asset_id LIMIT 2001", (r, n) -> {
long id = r.getLong("catalog_asset_id"), catalog = r.getLong("catalog_id"), version = r.getLong("version");
if (id <= 0 || !ids.add(id) || version < 0 || catalogs.stream().noneMatch(c -> c.id() == catalog))
throw AssetCatalogDomainException.conflict("资产登记范围不完整");
return new Registration(Long.toString(id), Long.toString(catalog), r.getString("asset_ref"),
r.getString("asset_name"), r.getString("asset_type"), "1".equals(r.getString("reliable_flag")), version);
}, args.toArray());
if (rows.size() > 2_000) throw AssetCatalogDomainException.conflict("登记超过 2000 条,请选择单个目录后读取");
return rows;
}
public Portfolio portfolio() {
try {
Actor actor = actors.current();
actors.requireCurrent(actor, PURPOSE);
var before = visible(actor);
var first = grouped(actor, before);
var second = grouped(actor, before);
var after = visible(actor);
actors.requireCurrent(actor, PURPOSE);
if (!before.equals(after) || !first.equals(second)) {
throw AssetCatalogDomainException.conflict("资产目录范围或统计已变化,请重新读取");
}
var groups = after.stream().map(catalog -> new CatalogGroup(Long.toString(catalog.id()),
catalog.name(), catalog.status(), second.stream().filter(row -> row.catalogId() == catalog.id())
.map(row -> new TypeCount(row.type(), row.reliable(), row.uncertain())).toList())).toList();
return new Portfolio(scopeSha(actor, after), java.time.Instant.now(), second.stream()
.map(GroupedCount::updatedAt).filter(java.util.Objects::nonNull).max(Comparator.naturalOrder()).orElse(null),
"REGISTRATION", false, groups);
} catch (AssetCatalogDomainException rejected) {
throw rejected;
} catch (RuntimeException unavailable) {
throw AssetCatalogDomainException.conflict("资产目录统计暂不可用");
}
}
private List<GroupedCount> grouped(Actor actor, List<CatalogRevision> catalogs) {
if (catalogs.isEmpty()) return List.of();
var args = new ArrayList<Object>(List.of(actor.organizationId(), actor.departmentId()));
catalogs.forEach(catalog -> args.add(catalog.id()));
String sql = "SELECT catalog_id,CASE WHEN asset_type IN ('TABLE','DATASET','FILE','REPORT','API','MODEL') "
+ "THEN asset_type ELSE 'UNKNOWN' END AS kind,"
+ "SUM(CASE WHEN reliable_flag='1' THEN 1 ELSE 0 END) AS reliable_count,"
+ "SUM(CASE WHEN reliable_flag='1' THEN 0 ELSE 1 END) AS uncertain_count,MAX(update_time) AS updated_at "
+ "FROM asset_catalog_item WHERE organization_id=? AND department_id=? AND del_flag='0' AND catalog_id IN ("
+ String.join(",", java.util.Collections.nCopies(catalogs.size(), "?"))
+ ") GROUP BY catalog_id,kind ORDER BY catalog_id,kind";
return jdbc.query(sql, (r, n) -> {
long id = r.getLong("catalog_id"), reliable = r.getLong("reliable_count"), uncertain = r.getLong("uncertain_count");
var updated = r.getTimestamp("updated_at");
if (reliable < 0 || uncertain < 0 || updated == null || catalogs.stream().noneMatch(c -> c.id() == id)) {
throw AssetCatalogDomainException.conflict("资产目录统计结果不可用");
}
return new GroupedCount(id, r.getString("kind"), reliable, uncertain, updated.toLocalDateTime());
}, args.toArray());
}
public Observation current() {
try {
Actor actor = actors.current();
actors.requireCurrent(actor, PURPOSE);
List<CatalogRevision> before = visible(actor);
Aggregate first = aggregate(actor, before);
Aggregate second = aggregate(actor, before);
// The second directory read follows both aggregate reads, so a catalog grant
// revoked during SQL cannot be accepted just because the menu grant remains.
List<CatalogRevision> after = visible(actor);
actors.requireCurrent(actor, PURPOSE);
if (!before.equals(after) || !first.equals(second)) {
throw AssetCatalogDomainException.conflict("资产目录范围或统计已变化,请重新读取");
}
return new Observation(actor.actorId(), actor.organizationId(), actor.departmentId(),
second.count(), second.observedAt(), scopeSha(actor, after));
} catch (AssetCatalogDomainException rejected) {
throw rejected;
} catch (RuntimeException unavailable) {
// Never expose SQL, connection details, or fall back to the whole department.
throw AssetCatalogDomainException.conflict("资产目录统计暂不可用");
}
}
private List<CatalogRevision> visible(Actor actor) {
var nodes = repository.tree(actor, CatalogAction.VIEW);
if (nodes == null) throw AssetCatalogDomainException.conflict("资产目录范围不可用");
if (nodes.size() > MAX_VISIBLE_CATALOGS) {
throw AssetCatalogDomainException.conflict("可见目录超过 1000 个,暂不提供汇总统计");
}
Set<Long> ids = new HashSet<>();
List<CatalogRevision> result = new ArrayList<>(nodes.size());
for (var node : nodes) {
if (node == null || node.catalogId() <= 0 || node.version() < 0
|| node.organizationId() != actor.organizationId()
|| node.departmentId() != actor.departmentId() || !ids.add(node.catalogId())) {
throw AssetCatalogDomainException.conflict("资产目录范围不完整");
}
result.add(new CatalogRevision(node.catalogId(), node.version(), node.catalogName(), node.status().name()));
}
result.sort(Comparator.comparingLong(CatalogRevision::id));
return List.copyOf(result);
}
private Aggregate aggregate(Actor actor, List<CatalogRevision> catalogs) {
if (catalogs.isEmpty()) return new Aggregate(0, null);
String placeholders = String.join(",", java.util.Collections.nCopies(catalogs.size(), "?"));
String sql = "SELECT COUNT(*) AS asset_count,MAX(update_time) AS observed_at "
+ "FROM asset_catalog_item WHERE organization_id=? AND department_id=? "
+ "AND del_flag='0' AND reliable_flag='1' AND catalog_id IN (" + placeholders + ")";
List<Object> arguments = new ArrayList<>(catalogs.size() + 2);
arguments.add(actor.organizationId());
arguments.add(actor.departmentId());
catalogs.forEach(catalog -> arguments.add(catalog.id()));
List<Aggregate> values = jdbc.query(sql, (rows, index) -> {
long count = rows.getLong("asset_count");
if (rows.wasNull() || count < 0) {
throw AssetCatalogDomainException.conflict("资产目录统计数量不可用");
}
var timestamp = rows.getTimestamp("observed_at");
if ((count == 0) != (timestamp == null)) {
throw AssetCatalogDomainException.conflict("资产目录统计时间不可用");
}
return new Aggregate(count, timestamp == null ? null : timestamp.toLocalDateTime());
}, arguments.toArray());
if (values == null || values.size() != 1 || values.getFirst() == null) {
throw AssetCatalogDomainException.conflict("资产目录统计结果不可用");
}
return values.getFirst();
}
private static String scopeSha(Actor actor, List<CatalogRevision> catalogs) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
text(digest, "asset-catalog-overview-scope-v1");
text(digest, PURPOSE);
number(digest, actor.actorId());
number(digest, actor.organizationId());
number(digest, actor.departmentId());
strings(digest, actor.roles());
strings(digest, actor.permissions());
strings(digest, actor.subjectRefs());
number(digest, catalogs.size());
for (CatalogRevision catalog : catalogs) {
number(digest, catalog.id());
number(digest, catalog.version());
}
return HexFormat.of().formatHex(digest.digest());
} catch (NoSuchAlgorithmException unavailable) {
throw AssetCatalogDomainException.conflict("资产目录范围摘要不可用");
}
}
private static void strings(MessageDigest digest, Set<String> values) {
List<String> sorted = values.stream().sorted().toList();
number(digest, sorted.size());
sorted.forEach(value -> text(digest, value));
}
private static void text(MessageDigest digest, String value) {
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
number(digest, bytes.length);
digest.update(bytes);
}
private static void number(MessageDigest digest, long value) {
digest.update(ByteBuffer.allocate(Long.BYTES).putLong(value).array());
}
private record CatalogRevision(long id, long version, String name, String status) { }
private record Aggregate(long count, LocalDateTime observedAt) { }
private record GroupedCount(long catalogId, String type, long reliable, long uncertain, LocalDateTime updatedAt) { }
}
@@ -0,0 +1,127 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
@Component
@RequiredArgsConstructor
class AssetCatalogPolicy {
static final int MAX_DEPTH = 12;
static final int MAX_ASSETS = 500;
private static final Pattern IDEMPOTENCY = Pattern.compile("[A-Za-z0-9._:-]{16,128}");
private static final Pattern CODE = Pattern.compile("[A-Za-z][A-Za-z0-9_-]{1,63}");
private static final Pattern SAFE_REF = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:/@-]{0,511}");
private static final Pattern ASSET_FQN = Pattern.compile("[\\p{L}\\p{N}_-]+(?:\\.[\\p{L}\\p{N}_-]+)*");
private static final Pattern SHA256 = Pattern.compile("[a-fA-F0-9]{64}");
private static final Pattern DANGEROUS = Pattern.compile("(?is).*(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|CALL|EXEC|SCRIPT|SHELL)\\b|https?://|jdbc:|password|secret|token|credential|\\.\\./|\\\\).*");
private final JsonMapper mapper;
String idempotencyKey(String value) {
if (value == null || value.isBlank()) throw AssetCatalogDomainException.validation("Idempotency-Key不能为空");
String normalized = value.trim();
if (normalized.length() < 16 || normalized.length() > 128 || !IDEMPOTENCY.matcher(normalized).matches()) {
throw AssetCatalogDomainException.validation("Idempotency-Key格式无效");
}
return normalized;
}
CreateNodeCommand normalize(CreateNodeCommand value) {
if (value == null) throw AssetCatalogDomainException.validation("目录请求不能为空");
return new CreateNodeCommand(matched(required(value.catalogCode(), "目录编码", 64), CODE, "目录编码格式无效"),
required(value.catalogName(), "目录名称", 200), positiveOrNull(value.parentId(), "父目录ID"),
optional(value.description(), "目录描述", 1000), sort(value.sortOrder()));
}
UpdateNodeCommand normalize(UpdateNodeCommand value) {
version(value == null ? null : value.version());
return new UpdateNodeCommand(required(value.catalogName(), "目录名称", 200),
optional(value.description(), "目录描述", 1000), sort(value.sortOrder()), value.version());
}
MoveNodeCommand normalize(MoveNodeCommand value) {
version(value == null ? null : value.version());
return new MoveNodeCommand(positiveOrNull(value.parentId(), "父目录ID"), sort(value.sortOrder()), value.version());
}
CatalogAssetCommand normalize(CatalogAssetCommand value, LocalDateTime now) {
if (value == null || value.assetType() == null) throw AssetCatalogDomainException.validation("编目请求不完整");
version(value.version());
LocalDateTime observedAt = value.observedAt();
if (observedAt == null || observedAt.isAfter(now.plusMinutes(5)) || observedAt.isBefore(now.minusHours(24))) {
throw AssetCatalogDomainException.validation("来源观测时间无效或已过期");
}
if (!value.reliable()) throw AssetCatalogDomainException.conflict("不可靠来源资产只能保留在上游草稿,禁止编目发布");
List<String> tags = value.tags() == null ? List.of() : value.tags().stream()
.map(tag -> required(tag, "标签", 64)).distinct().sorted().toList();
if (tags.size() > 50) throw AssetCatalogDomainException.validation("标签最多50项");
return new CatalogAssetCommand(safeRef(value.assetRef(), "资产引用"), assetFqn(value.assetFqn()),
value.assetType(), required(value.assetName(), "资产名称", 200), optional(value.description(), "资产描述", 2000),
tags, ownerType(value.ownerType()), safeRef(value.ownerRef(), "Owner引用"),
safeRef(value.sourceType(), "来源类型"), safeRef(value.sourceRef(), "来源引用"), observedAt, true,
sha(value.payloadSha256()), value.version());
}
PublishCommand normalize(PublishCommand value) {
version(value == null ? null : value.version());
return new PublishCommand(required(value.reason(), "发布原因", 500), value.version());
}
StatusCommand normalize(StatusCommand value) {
if (value == null || value.targetStatus() == null) throw AssetCatalogDomainException.validation("状态请求不完整");
version(value.version());
return new StatusCommand(value.targetStatus(), required(value.reason(), "状态原因", 500), value.version());
}
PermissionCommand normalize(PermissionCommand value, LocalDateTime now) {
if (value == null || value.subjectType() == null || value.actions() == null || value.actions().isEmpty()) {
throw AssetCatalogDomainException.validation("目录权限请求不完整");
}
version(value.version());
List<CatalogAction> actions = value.actions().stream().filter(Objects::nonNull).distinct().sorted().toList();
if (actions.size() != value.actions().size()) throw AssetCatalogDomainException.validation("目录权限动作无效或重复");
LocalDateTime from = value.effectiveFrom() == null ? now : value.effectiveFrom();
if (value.effectiveTo() != null && !value.effectiveTo().isAfter(from)) throw AssetCatalogDomainException.validation("权限有效期无效");
return new PermissionCommand(value.subjectType(), safeRef(value.subjectRef(), "RCP6主体引用"), actions,
value.includeDescendants(), from, value.effectiveTo(), required(value.reason(), "授权原因", 500), value.version());
}
void requireTransition(CatalogStatus current, CatalogStatus target) {
boolean allowed = current == CatalogStatus.PUBLISHED && target == CatalogStatus.UNPUBLISHED;
if (!allowed) throw AssetCatalogDomainException.conflict("目录状态不允许该转换");
}
void requirePublishable(List<AssetView> assets, LocalDateTime now) {
if (assets.isEmpty()) throw AssetCatalogDomainException.conflict("无编目资产,禁止发布");
if (assets.size() > MAX_ASSETS) throw AssetCatalogDomainException.conflict("单次发布资产超过500项上限");
boolean invalid = assets.stream().anyMatch(asset -> !asset.reliable()
|| asset.observedAt() == null || asset.observedAt().isAfter(now.plusMinutes(5))
|| asset.observedAt().isBefore(now.minusHours(24))
|| asset.payloadSha256() == null || !SHA256.matcher(asset.payloadSha256()).matches());
if (invalid) throw AssetCatalogDomainException.conflict("编目来源不可靠、过期或SHA无效,禁止发布");
}
String requestHash(Object value) { return sha256(write(value)); }
String snapshotSha(List<AssetView> assets) { return sha256(write(assets)); }
private static int sort(Integer value) {
if (value == null) return 0;
if (value < 0 || value > 999_999) throw AssetCatalogDomainException.validation("目录排序值无效");
return value;
}
private static void version(Long value) { if (value == null || value < 0) throw AssetCatalogDomainException.validation("version无效"); }
private static Long positiveOrNull(Long value, String label) { if (value != null && value <= 0) throw AssetCatalogDomainException.validation(label + "无效"); return value; }
private static String safeRef(String value, String label) { return matched(required(value, label, 512), SAFE_REF, label + "格式无效"); }
private static String assetFqn(String value) { return matched(required(value, "资产FQN", 512), ASSET_FQN, "资产FQN格式无效"); }
private static String ownerType(String value) {
String normalized = safeRef(value, "Owner类型");
try { SubjectType.valueOf(normalized); return normalized; }
catch (IllegalArgumentException exception) { throw AssetCatalogDomainException.validation("Owner类型必须引用RCP6主体"); }
}
private static String sha(String value) { return matched(required(value, "payloadSha256", 64).toLowerCase(Locale.ROOT), SHA256, "payloadSha256必须为SHA-256"); }
private static String optional(String value, String label, int max) { return value == null || value.isBlank() ? null : checked(value.trim(), label, max); }
private static String required(String value, String label, int max) { if (value == null || value.isBlank()) throw AssetCatalogDomainException.validation(label + "不能为空"); return checked(value.trim(), label, max); }
private static String checked(String value, String label, int max) { if (value.length() > max || DANGEROUS.matcher(value).matches()) throw AssetCatalogDomainException.validation(label + "格式无效"); return value; }
private static String matched(String value, Pattern pattern, String message) { if (!pattern.matcher(value).matches()) throw AssetCatalogDomainException.validation(message); return value; }
private String write(Object value) { try { return mapper.writeValueAsString(value); } catch (JacksonException e) { throw AssetCatalogDomainException.validation("请求无法序列化"); } }
private static String sha256(String value) { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("SHA-256不可用", e); } }
}
@@ -0,0 +1,131 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
@Service
@RequiredArgsConstructor
class AssetCatalogService {
private static final String BASE = "/api/governance/v1/asset-catalogs";
private final AssetCatalogJdbcRepository repository;
private final AssetCatalogPolicy policy;
private final AssetCatalogActorProvider actorProvider;
private final TransactionTemplate transactions;
private final AssetCatalogInventorySource inventorySource;
List<NodeView> tree() { var actor = actorProvider.current(); return repository.tree(actor, CatalogAction.VIEW); }
DetailView detail(long id) { var actor = actorProvider.current(); repository.authorize(actor, positive(id), CatalogAction.VIEW); return repository.detail(id, actor); }
WriteView<DetailView> create(String key, CreateNodeCommand raw) {
actorProvider.require("ASSET_CATALOG_CREATE");
var actor = actorProvider.current(); var command = policy.normalize(raw);
if (command.parentId() != null) repository.authorize(actor, command.parentId(), CatalogAction.MAINTAIN);
else if (!actor.administrator()) throw AssetCatalogDomainException.forbidden();
return execute(actor, "POST", BASE, key, command, ticket -> {
long id = repository.create(actor, command);
repository.trajectory(actor, id, "CREATE", null, CatalogStatus.DRAFT.name(), ticket.requestId(), "目录草稿已创建");
if(command.parentId()!=null)repository.authorize(actor,command.parentId(),CatalogAction.MAINTAIN);actorProvider.requireCurrent(actor,"ASSET_CATALOG_CREATE");
return new Mutation<>(id, repository.detail(id, actor));
}, id -> repository.detail(id, actor));
}
WriteView<DetailView> update(long rawId, String key, UpdateNodeCommand raw) {
actorProvider.require("ASSET_CATALOG_UPDATE");
long id = positive(rawId); var actor = actorProvider.current(); repository.authorize(actor, id, CatalogAction.MAINTAIN); var command = policy.normalize(raw);
return execute(actor, "PATCH", BASE + '/' + id, key, command, ticket -> {
repository.update(actor, id, command); repository.trajectory(actor, id, "UPDATE", null, null, ticket.requestId(), "目录信息已更新");
repository.authorize(actor,id,CatalogAction.MAINTAIN);actorProvider.requireCurrent(actor,"ASSET_CATALOG_UPDATE");
return new Mutation<>(id, repository.detail(id, actor));
}, replay -> repository.detail(replay, actor));
}
WriteView<DetailView> move(long rawId, String key, MoveNodeCommand raw) {
actorProvider.require("ASSET_CATALOG_UPDATE");
long id = positive(rawId); var actor = actorProvider.current(); repository.authorize(actor, id, CatalogAction.MAINTAIN); var command = policy.normalize(raw);
if (command.parentId() != null) repository.authorize(actor, command.parentId(), CatalogAction.MAINTAIN);
return execute(actor, "PUT", BASE + '/' + id + "/parent", key, command, ticket -> {
repository.move(actor, id, command); repository.trajectory(actor, id, "MOVE", null, null, ticket.requestId(), "目录父子关系已无环更新");
repository.authorize(actor,id,CatalogAction.MAINTAIN);if(command.parentId()!=null)repository.authorize(actor,command.parentId(),CatalogAction.MAINTAIN);actorProvider.requireCurrent(actor,"ASSET_CATALOG_UPDATE");
return new Mutation<>(id, repository.detail(id, actor));
}, replay -> repository.detail(replay, actor));
}
WriteView<DetailView> catalog(long rawId, String key, CatalogAssetCommand raw) {
long id = positive(rawId); var actor = actorProvider.current(); repository.authorize(actor, id, CatalogAction.MAINTAIN);
var command = policy.normalize(raw, LocalDateTime.now());
return execute(actor, "POST", BASE + '/' + id + "/assets", key, command, ticket -> {
repository.catalog(actor, id, command); repository.trajectory(actor, id, "CATALOG", null, null, ticket.requestId(), "可靠来源资产已编目");
return new Mutation<>(id, repository.detail(id, actor));
}, replay -> repository.detail(replay, actor));
}
WriteView<DetailView> catalogFromInventory(long rawCatalogId, String key, InventoryCatalogCommand raw) {
return catalogFromInventory(rawCatalogId, key, raw, null);
}
WriteView<DetailView> catalogFromInventory(long rawCatalogId, String key, InventoryCatalogCommand raw, String expectedSourceSha) {
if (raw == null || raw.taskId() <= 0 || raw.candidateId() <= 0 || raw.candidateVersion() < 0
|| raw.version() == null || raw.version() < 0) throw AssetCatalogDomainException.validation("盘点编目身份或版本无效");
long catalogId = positive(rawCatalogId); var actor = actorProvider.current();
repository.authorize(actor, catalogId, CatalogAction.MAINTAIN);
return execute(actor, "POST", BASE + '/' + catalogId + "/inventory-assets", key, raw, ticket -> {
var source = inventorySource.read(raw.taskId(), raw.candidateId(), actor);
if (expectedSourceSha != null && !expectedSourceSha.equals(
cn.aixunkeji.datagov.governance.scheduling.GovernanceSchedulingDubboService.hash(source))) {
throw AssetCatalogDomainException.conflict("盘点确认依据已变化,请重新发布流程");
}
CatalogAssetCommand command = policy.normalize(
source.command(raw), LocalDateTime.now());
repository.catalog(actor, catalogId, command); repository.trajectory(actor, catalogId, "CATALOG", null, null, ticket.requestId(), "已确认盘点资产编目");
return new Mutation<>(catalogId, repository.detail(catalogId, actor));
}, replay -> repository.detail(replay, actor));
}
WriteView<PublicationView> publish(long rawId, String key, PublishCommand raw) {
long id = positive(rawId); var actor = actorProvider.current(); repository.authorize(actor, id, CatalogAction.PUBLISH); var command = policy.normalize(raw);
return execute(actor, "POST", BASE + '/' + id + "/publications", key, command, ticket -> {
List<AssetView> assets = repository.assets(id, actor);
policy.requirePublishable(assets, LocalDateTime.now());
CatalogStatus beforeStatus = repository.node(id, actor).status();
PublicationView publication = repository.publish(actor, id, command, policy.snapshotSha(assets), assets);
repository.trajectory(actor, id, "PUBLISH", beforeStatus.name(), CatalogStatus.PUBLISHED.name(), ticket.requestId(), command.reason());
return new Mutation<>(publication.publicationId(), publication);
}, repository::publication);
}
WriteView<PermissionView> permission(long rawId, String key, PermissionCommand raw) {
long id = positive(rawId); var actor = actorProvider.current(); repository.authorize(actor, id, CatalogAction.PERMISSION); var command = policy.normalize(raw, LocalDateTime.now());
return execute(actor, "POST", BASE + '/' + id + "/permissions", key, command, ticket -> {
PermissionView permission = repository.permission(actor, id, command);
repository.trajectory(actor, id, "PERMISSION", null, null, ticket.requestId(), "RCP6主体引用目录权限已追加");
return new Mutation<>(permission.permissionId(), permission);
}, repository::permission);
}
WriteView<DetailView> status(long rawId, String key, StatusCommand raw) {
long id = positive(rawId); var actor = actorProvider.current(); repository.authorize(actor, id, CatalogAction.PUBLISH); var command = policy.normalize(raw);
return execute(actor, "POST", BASE + '/' + id + "/status", key, command, ticket -> {
NodeView node = repository.node(id, actor); policy.requireTransition(node.status(), command.targetStatus());
repository.status(actor, id, node.status(), command); repository.trajectory(actor, id, "STATUS", node.status().name(), command.targetStatus().name(), ticket.requestId(), command.reason());
return new Mutation<>(id, repository.detail(id, actor));
}, replay -> repository.detail(replay, actor));
}
private <T> WriteView<T> execute(AssetCatalogActorProvider.Actor actor, String method, String path,
String rawKey, Object command,
Function<AssetCatalogJdbcRepository.RequestTicket, Mutation<T>> work,
Function<Long, T> replay) {
String key = policy.idempotencyKey(rawKey); String hash = policy.requestHash(command);
var ticket = repository.begin(actor, method, path, key, hash);
if (ticket.responseId() != null) return new WriteView<>(ticket.requestId(), replay.apply(ticket.responseId()));
try {
Mutation<T> result = transactions.execute(status -> { Mutation<T> changed = work.apply(ticket); repository.complete(actor, method, path, key, changed.responseId()); return changed; });
if (result == null) throw new IllegalStateException("资产目录事务未返回结果");
return new WriteView<>(ticket.requestId(), result.result());
} catch (RuntimeException exception) {
try { repository.fail(actor, method, path, key); }
catch (RuntimeException recording) { exception.addSuppressed(recording); }
throw exception;
}
}
private static long positive(long id) { if (id <= 0) throw AssetCatalogDomainException.validation("目录ID无效"); return id; }
private record Mutation<T>(long responseId, T result) { }
}
@@ -0,0 +1,27 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.common.log.annotation.Log;
import cn.aixunkeji.common.log.enums.BusinessType;
import cn.aixunkeji.datagov.dataproduct.api.catalogidentity.CatalogIdentityOwner.Source;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
@RestController @RequiredArgsConstructor
@RequestMapping("/api/governance/v1/asset-catalogs/registrations/{registrationId}/source-identity")
@SaCheckPermission("aixun:governance:asset-catalog:view")
public class AssetCatalogSourceIdentityController {
private final AssetCatalogSourceIdentityService service;
@GetMapping public R<AssetCatalogSourceIdentityService.Inspection> inspect(@PathVariable long registrationId){return R.ok(service.inspect(registrationId));}
@GetMapping("/candidates") public R<PageResult<Source>> candidates(@PathVariable long registrationId,@RequestParam(required=false)String keyword,@RequestParam(required=false)Integer pageNum,@RequestParam(required=false)Integer pageSize){return R.ok(service.candidates(registrationId,keyword,pageNum,pageSize));}
@GetMapping("/preview") public R<AssetCatalogSourceIdentityService.Preview> preview(@PathVariable long registrationId,@RequestParam String sourceRef){return R.ok(service.preview(registrationId,sourceRef));}
@PostMapping @SaCheckPermission("aixun:governance:asset-catalog:catalog")
@Log(title="登记来源身份关联",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
public R<AssetCatalogSourceIdentityService.LinkView> link(@PathVariable long registrationId,@RequestHeader("Idempotency-Key")String key,@RequestBody AssetCatalogSourceIdentityService.Command command){return R.ok(service.link(registrationId,key,command));}
@GetMapping("/requests/{key}") public R<AssetCatalogSourceIdentityService.Receipt> request(@PathVariable long registrationId,@PathVariable String key){return R.ok(service.request(registrationId,key));}
@PostMapping("/requests/{key}/cancel") @SaCheckPermission("aixun:governance:asset-catalog:catalog")
@Log(title="结束未提交来源关联请求",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
public R<AssetCatalogSourceIdentityService.Receipt> cancel(@PathVariable long registrationId,@PathVariable String key){return R.ok(service.cancel(registrationId,key));}
}
@@ -0,0 +1,41 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.time.Instant;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogActorProvider.Actor;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogIdentityLinkRepository.Registration;
@Repository @RequiredArgsConstructor
class AssetCatalogSourceIdentityRepository {
private final JdbcTemplate jdbc;
record Link(long id,long registrationId,long catalogId,long registrationVersion,long version,String assetRef,
String type,String owner,String sourceId,String sourceVersion,String sourceCode,String sourceName,
String evidenceSha256,Instant expiresAt,Instant linkedAt,String requestId) {
Link(long id,long registrationId,long catalogId,long registrationVersion,long version,String assetRef,
String type,String owner,long sourceId,String sourceVersion,String sourceCode,String sourceName,
String evidenceSha256,Instant expiresAt,Instant linkedAt,String requestId) {
this(id,registrationId,catalogId,registrationVersion,version,assetRef,type,owner,Long.toString(sourceId),sourceVersion,sourceCode,sourceName,evidenceSha256,expiresAt,linkedAt,requestId);
}
}
Link latest(Actor actor,long registrationId) { return find(actor,"catalog_asset_id=? ORDER BY link_version DESC LIMIT 1",registrationId); }
Link get(Actor actor,long id) {
Link value=find(actor,"link_id=?",id);
if(value==null)throw AssetCatalogDomainException.conflict("来源身份回执暂不可用");
return value;
}
private Link find(Actor actor,String condition,long id) {
return jdbc.query("SELECT link_id,catalog_asset_id,catalog_id,registration_version,link_version,asset_ref,asset_type,source_owner,source_id,source_version,source_code,source_name,evidence_sha256,evidence_expires_at,create_time,request_id FROM asset_catalog_source_identity_link WHERE organization_id=? AND department_id=? AND del_flag='0' AND "+condition,
(r,n)->new Link(r.getLong(1),r.getLong(2),r.getLong(3),r.getLong(4),r.getLong(5),r.getString(6),r.getString(7),r.getString(8),r.getString(9),r.getString(10),r.getString(11),r.getString(12),r.getString(13),r.getTimestamp(14).toInstant(),r.getTimestamp(15).toInstant(),r.getString(16)),actor.organizationId(),actor.departmentId(),id).stream().findFirst().orElse(null);
}
Link insert(Actor actor,Registration registration,long version,AssetCatalogSourceIdentityService.Proof proof,String requestId) {
long id=IdGeneratorUtil.nextLongId();var source=proof.source();
jdbc.update("INSERT INTO asset_catalog_source_identity_link(link_id,catalog_asset_id,catalog_id,registration_version,link_version,asset_ref,asset_type,source_owner,source_id,source_version,source_code,source_name,evidence_sha256,evidence_expires_at,actor_id,organization_id,department_id,request_id,create_dept,create_by,update_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
id,registration.id(),registration.catalogId(),registration.version(),version,registration.assetRef(),
registration.type(),cn.aixunkeji.datagov.dataproduct.api.catalogidentity.CatalogIdentityOwner.owner(registration.type()),AssetCatalogSourceIdentityService.sourceId(registration.type(),source.sourceRef()),source.sourceVersion(),source.sourceCode(),source.sourceName(),proof.sha256(),Timestamp.from(proof.expiresAt()),actor.actorId(),actor.organizationId(),actor.departmentId(),requestId,actor.departmentId(),actor.actorId(),actor.actorId());
return get(actor,id);
}
}
@@ -0,0 +1,222 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.common.core.domain.PageResult;
import cn.aixunkeji.datagov.governance.modeldesign.ModelDesignSourceFacade;
import cn.aixunkeji.datagov.dataproduct.api.catalogidentity.CatalogIdentityOwner;
import cn.aixunkeji.datagov.dataproduct.api.catalogidentity.CatalogIdentityOwner.Source;
import cn.aixunkeji.common.core.exception.ServiceException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogActorProvider.Actor;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.CatalogAction;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogIdentityLinkRepository.Registration;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogIdentityLinkRepository.Request;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogSourceIdentityRepository.Link;
/** Explicit registered-type -> existing Owner identity. No inferred IDs or lifecycle mutations. */
@Service
class AssetCatalogSourceIdentityService {
static final String READ="ASSET_CATALOG_MODEL_VIEW", WRITE="ASSET_CATALOG_MODEL_LINK";
private final AssetCatalogActorProvider actors;
private final AssetCatalogJdbcRepository catalogs;
private final AssetCatalogIdentityLinkRepository requests;
private final AssetCatalogSourceIdentityRepository repository;
private final ModelDesignSourceFacade models;
@DubboReference(version=CatalogIdentityOwner.VERSION,check=false,timeout=20000,retries=0)
private CatalogIdentityOwner sources;
private final AssetCatalogPolicy policy;
private final TransactionTemplate transactions;
AssetCatalogSourceIdentityService(AssetCatalogActorProvider actors,AssetCatalogJdbcRepository catalogs,
AssetCatalogIdentityLinkRepository requests,AssetCatalogSourceIdentityRepository repository,
ModelDesignSourceFacade models,AssetCatalogPolicy policy,TransactionTemplate shared) {
this.actors=actors;this.catalogs=catalogs;this.requests=requests;this.repository=repository;this.models=models;this.policy=policy;
this.transactions=new TransactionTemplate(Objects.requireNonNull(shared.getTransactionManager()),shared);
this.transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
}
record Command(Long registrationVersion,Long expectedLinkVersion,String sourceRef,String sourceVersion,String evidenceSha256) { }
record Proof(Source source,String sha256,Instant expiresAt) { }
record Preview(String registrationId,String registrationVersion,String type,String owner,Source source,
String evidenceSha256,Instant expiresAt) { }
record LinkView(String linkId,String registrationId,String version,String type,String owner,String sourceRef,
String sourceVersion,String sourceCode,String sourceName,String evidenceSha256,Instant expiresAt,
Instant linkedAt,String requestId) { }
record Inspection(String registrationId,String registrationVersion,String assetRef,String associationState,
LinkView link,Preview current,Instant readAt) { }
record Receipt(String state,String registrationId,String requestKey,LinkView link) { }
PageResult<Source> candidates(long id,String keyword,Integer page,Integer size) {
Actor actor=actor("ASSET_CATALOG_VIEW");Registration before=registration(actor,id,CatalogAction.VIEW,false);
String purpose=purpose(before.type(),false);actors.requireCurrent(actor,purpose);
PageResult<Source> result;
if("MODEL".equals(before.type())) {
var values=owner(()->models.candidates(keyword,page,size));
result=PageResult.build(values.getRows().stream().map(AssetCatalogSourceIdentityService::model).toList(),values.getTotal());
} else {
var values=owner(()->sources.candidates(before.type(),keyword,page==null?1:page,size==null?10:size));
if(values==null||values.total()<0||values.rows()==null||values.rows().size()>(size==null?10:size))throw AssetCatalogDomainException.conflict("来源候选暂不可用");
for(var value:values.rows())validateSource(before.type(),value);
result=PageResult.build(values.rows(),values.total());
}
unchanged(actor,before);actors.requireCurrent(actor,purpose);return result;
}
Preview preview(long id,String sourceRef) {
Actor actor=actor("ASSET_CATALOG_VIEW");Registration before=registration(actor,id,CatalogAction.VIEW,false);
String purpose=purpose(before.type(),false);actors.requireCurrent(actor,purpose);
Proof proof=observe(actor,before.type(),sourceRef);
unchanged(actor,before);actors.requireCurrent(actor,purpose);return preview(before,proof);
}
Inspection inspect(long id) {
Actor actor=actor("ASSET_CATALOG_VIEW");Registration before=registration(actor,id,CatalogAction.VIEW,false);
String purpose=purpose(before.type(),false);actors.requireCurrent(actor,purpose);
Link link=repository.latest(actor,id);Proof current=null;String state=link==null?"UNLINKED":"UNKNOWN";
if(link!=null) {
if(!before.type().equals(link.type())||!CatalogIdentityOwner.owner(before.type()).equals(link.owner())||link.registrationVersion()!=before.version()
||!Objects.equals(link.assetRef(),before.assetRef())) state="STALE";
else {
try {
current=observe(actor,before.type(),CatalogIdentityOwner.prefix(link.type())+link.sourceId());
state=current.source().sourceRef().equals(CatalogIdentityOwner.prefix(link.type())+link.sourceId())
&&current.source().sourceVersion().equals(link.sourceVersion())&&current.sha256().equals(link.evidenceSha256())?"CURRENT":"STALE";
} catch(AssetCatalogDomainException rejected) {
if(rejected.code()==AssetCatalogDomainException.FORBIDDEN_CODE)throw rejected;
// The prior association remains visible as history, never as a current count.
}
}
}
unchanged(actor,before);actors.requireCurrent(actor,purpose);
if(!Objects.equals(link,repository.latest(actor,id)))throw AssetCatalogDomainException.conflict("来源关联已变化,请重新读取");
return new Inspection(Long.toString(id),Long.toString(before.version()),before.assetRef(),state,view(link),
current==null?null:preview(before,current),Instant.now());
}
LinkView link(long id,String rawKey,Command command) {
validate(command);String key=policy.idempotencyKey(rawKey),path=path(id),hash=policy.requestHash(command);
Actor actor=actor("ASSET_CATALOG_VIEW");Registration before=registration(actor,id,CatalogAction.MAINTAIN,false);
String purpose=purpose(before.type(),true);actors.requireCurrent(actor,purpose);sourceId(before.type(),command.sourceRef());
var receipt=requests.receipt(actor,path,key);
if(receipt!=null)return replay(actor,before,receipt,hash);
if(canceled(requests.request(actor,path,key),cancelHash(actor,id,key)))throw AssetCatalogDomainException.conflict("原请求已结束且未写入,请重新核验后关联");
Proof proof=observe(actor,before.type(),command.sourceRef());require(command,proof);
return transactions.execute(status->{
Registration locked=registration(actor,id,CatalogAction.MAINTAIN,true);actors.requireCurrent(actor,purpose);
var ticket=catalogs.begin(actor,"POST",path,key,hash);
if(ticket.responseId()!=null)return replay(actor,locked,ticket,hash);
Link previous=repository.latest(actor,id);
if(!before.equals(locked)||locked.version()!=command.registrationVersion()
||(previous==null?0:previous.version())!=command.expectedLinkVersion())throw AssetCatalogDomainException.conflict("登记或来源关联版本已变化,请重新核验");
Source source=proof.source();
Source currentSource;
if("MODEL".equals(locked.type()))currentSource=model(owner(()->models.validateForCreate(source.sourceRef(),source.sourceCode(),source.sourceName(),source.sourceVersion())));
else currentSource=observe(actor,locked.type(),source.sourceRef()).source();
if(!source.equals(currentSource)||!proof.expiresAt().isAfter(Instant.now()))throw AssetCatalogDomainException.conflict("来源证据已变化或过期");
Link saved=repository.insert(actor,locked,command.expectedLinkVersion()+1,proof,ticket.requestId());
if(!"MODEL".equals(locked.type())&&!source.equals(observe(actor,locked.type(),source.sourceRef()).source()))throw AssetCatalogDomainException.conflict("来源版本已变化,请重新核验");
catalogs.authorize(actor,locked.catalogId(),CatalogAction.MAINTAIN);actors.requireCurrent(actor,purpose);
catalogs.trajectory(actor,locked.catalogId(),"SOURCE_IDENTITY_LINK",null,null,ticket.requestId(),"登记 "+id+" 显式关联 "+locked.type()+" 来源 "+saved.sourceId()+",关联版本 "+saved.version());
catalogs.complete(actor,"POST",path,key,saved.id());return view(saved);
});
}
Receipt request(long id,String rawKey) {
String key=policy.idempotencyKey(rawKey);Actor actor=actor("ASSET_CATALOG_VIEW");
Registration before=registration(actor,id,CatalogAction.VIEW,false);
String purpose=purpose(before.type(),false);actors.requireCurrent(actor,purpose);
Receipt result=receipt(actor,before,key,requests.request(actor,path(id),key));
unchanged(actor,before);actors.requireCurrent(actor,purpose);return result;
}
Receipt cancel(long id,String rawKey) {
String key=policy.idempotencyKey(rawKey);Actor actor=actor("ASSET_CATALOG_VIEW");
return transactions.execute(status->{
Registration locked=registration(actor,id,CatalogAction.MAINTAIN,true);String purpose=purpose(locked.type(),true);actors.requireCurrent(actor,purpose);
var existing=requests.request(actor,path(id),key);
if(existing==null) {
existing=requests.cancelUnobserved(actor,path(id),key,cancelHash(actor,id,key));
catalogs.trajectory(actor,locked.catalogId(),"SOURCE_IDENTITY_CANCEL",null,null,existing.requestId(),"登记 "+id+" 的未提交来源关联请求已结束");
}
Receipt result=receipt(actor,locked,key,existing);
catalogs.authorize(actor,locked.catalogId(),CatalogAction.MAINTAIN);actors.requireCurrent(actor,purpose);return result;
});
}
boolean stillCurrent(Actor actor,long registrationId,LinkView observed) {
Link latest=repository.latest(actor,registrationId);
return latest!=null&&observed!=null&&Long.toString(latest.id()).equals(observed.linkId())&&Long.toString(latest.version()).equals(observed.version());
}
Proof proof(Actor actor,ModelDesignSourceFacade.Source source) {return proof(actor,"MODEL",model(source),Instant.now().plusSeconds(300));}
private Proof proof(Actor actor,String type,Source source,Instant expires) {
validateSource(type,source);
return new Proof(source,policy.requestHash(List.of(type,CatalogIdentityOwner.owner(type),actor.organizationId(),actor.departmentId(),
source.sourceRef(),source.sourceVersion(),source.sourceCode(),source.sourceName())),expires);
}
private Proof observe(Actor actor,String type,String ref) {
sourceId(type,ref);
if("MODEL".equals(type)){var result=proof(actor,owner(()->models.observe(modelId(ref))));if(!ref.equals(result.source().sourceRef()))throw AssetCatalogDomainException.conflict("来源模型与选择不一致");return result;}
var value=owner(()->sources.observe(type,ref));Instant now=Instant.now();
if(value==null||!type.equals(value.type())||!CatalogIdentityOwner.owner(type).equals(value.owner())
||value.organizationId()!=actor.organizationId()||value.departmentId()!=actor.departmentId()||value.source()==null
||!ref.equals(value.source().sourceRef())||value.contentSha256()==null||!value.contentSha256().matches("[a-f0-9]{64}")
||value.observedAt()==null||value.observedAt().isBefore(now.minusSeconds(30))||value.observedAt().isAfter(now.plusSeconds(5))
||value.expiresAt()==null||!value.expiresAt().isAfter(now)||value.expiresAt().isAfter(now.plusSeconds(30)))throw AssetCatalogDomainException.conflict("来源身份、组织或版本证据无效");
return proof(actor,type,value.source(),value.expiresAt());
}
private static void validateSource(String type,Source source) {
if(source==null||source.sourceVersion()==null||!source.sourceVersion().matches("v(?:0|[1-9][0-9]*):[a-f0-9]{64}")
||source.sourceCode()==null||source.sourceCode().isBlank()||source.sourceCode().length()>200
||source.sourceName()==null||source.sourceName().isBlank()||source.sourceName().length()>200)throw AssetCatalogDomainException.conflict("来源版本无效");
sourceId(type,source.sourceRef());
}
private static Source model(ModelDesignSourceFacade.Source source){if(source==null)throw AssetCatalogDomainException.conflict("来源模型不可用");return new Source(source.sourceRef(),source.modelLogicalId(),source.modelDisplayName(),source.sourceVersion());}
static String purpose(String type,boolean write){CatalogIdentityOwner.owner(type);return "ASSET_CATALOG_"+type+(write?"_LINK":"_VIEW");}
static boolean supported(String type){return type!=null&&java.util.Set.of("MODEL","DATASET","FILE","API","REPORT").contains(type);}
static String sourceId(String type,String ref){try{return CatalogIdentityOwner.sourceId(type,ref);}catch(IllegalArgumentException invalid){throw AssetCatalogDomainException.validation("请选择对应类型的已有来源");}}
private Receipt receipt(Actor actor,Registration registration,String key,Request request) {
String state="NOT_OBSERVED";Link link=null;
if(request!=null) {
if("COMPLETED".equals(request.status())&&request.responseId()!=null) {
link=repository.get(actor,request.responseId());
if(link.registrationId()!=registration.id()||!link.requestId().equals(request.requestId())||!registration.type().equals(link.type())
||!CatalogIdentityOwner.owner(registration.type()).equals(link.owner()))throw AssetCatalogDomainException.conflict("原请求与当前登记类型或来源关联不一致");
state="COMPLETED";
} else if(canceled(request,cancelHash(actor,registration.id(),key)))state="CANCELED_NO_WRITE";
else state="PROCESSING".equals(request.status())?"PROCESSING":"UNKNOWN";
}
return new Receipt(state,Long.toString(registration.id()),key,view(link));
}
private LinkView replay(Actor actor,Registration registration,AssetCatalogJdbcRepository.RequestTicket ticket,String hash) {
if(!hash.equals(ticket.hash()))throw AssetCatalogDomainException.conflict("同一请求标识的关联内容不一致");
Link result=repository.get(actor,ticket.responseId());
if(result.registrationId()!=registration.id()||!result.requestId().equals(ticket.requestId())||!registration.type().equals(result.type())
||!CatalogIdentityOwner.owner(registration.type()).equals(result.owner()))throw AssetCatalogDomainException.conflict("原请求与当前登记类型或来源关联不一致");
actors.requireCurrent(actor,purpose(registration.type(),true));return view(result);
}
private Actor actor(String purpose){actors.require(purpose);Actor actor=actors.current();actors.requireCurrent(actor,purpose);return actor;}
private Registration registration(Actor actor,long id,CatalogAction action,boolean lock) {
if(id<=0)throw AssetCatalogDomainException.validation("登记标识无效");
Registration row=requests.registration(actor,id,lock);catalogs.authorize(actor,row.catalogId(),action);
if(!supported(row.type()))throw AssetCatalogDomainException.conflict("当前登记类型不支持此来源关联");return row;
}
private void unchanged(Actor actor,Registration before){if(!before.equals(registration(actor,before.id(),CatalogAction.VIEW,false)))throw AssetCatalogDomainException.conflict("登记已变化,请重新读取");}
static long modelId(String ref) {
if(ref==null||!ref.matches("model-design:[1-9][0-9]{0,18}"))throw AssetCatalogDomainException.validation("请选择已有模型来源");
try{return Long.parseLong(ref.substring("model-design:".length()));}catch(NumberFormatException invalid){throw AssetCatalogDomainException.validation("模型标识无效");}
}
private static void validate(Command c) {
if(c==null||c.registrationVersion()==null||c.registrationVersion()<0||c.expectedLinkVersion()==null||c.expectedLinkVersion()<0||c.expectedLinkVersion()==Long.MAX_VALUE
||c.sourceVersion()==null||c.sourceVersion().length()>128||c.evidenceSha256()==null||!c.evidenceSha256().matches("[a-f0-9]{64}"))throw AssetCatalogDomainException.validation("关联内容或版本无效");
if(c.sourceRef()==null||c.sourceRef().length()>200)throw AssetCatalogDomainException.validation("来源标识无效");
}
private static void require(Command c,Proof p){if(!c.sourceRef().equals(p.source().sourceRef())||!c.sourceVersion().equals(p.source().sourceVersion())||!c.evidenceSha256().equals(p.sha256()))throw AssetCatalogDomainException.conflict("选择的来源或版本已变化,请重新核验");}
private static <T>T owner(java.util.function.Supplier<T> call) {
try{return call.get();}catch(ModelDesignSourceFacade.SourceException failure){if(failure.code()==403)throw AssetCatalogDomainException.forbidden();throw AssetCatalogDomainException.conflict(failure.getMessage());}
catch(ServiceException failure){if(Integer.valueOf(403).equals(failure.getCode()))throw AssetCatalogDomainException.forbidden();throw AssetCatalogDomainException.conflict("来源当前不可核验,请重新读取");}
catch(AssetCatalogDomainException failure){throw failure;}
catch(RuntimeException unavailable){throw AssetCatalogDomainException.conflict("来源当前不可核验,请重新读取");}
}
private String cancelHash(Actor actor,long id,String key){return policy.requestHash(List.of("CATALOG_SOURCE_IDENTITY_CANCELED_NO_WRITE",actor.actorId(),actor.organizationId(),actor.departmentId(),id,key));}
private static boolean canceled(Request r,String hash){return r!=null&&"FAILED".equals(r.status())&&r.responseId()==null&&hash.equals(r.hash());}
private static Preview preview(Registration row,Proof p){return new Preview(Long.toString(row.id()),Long.toString(row.version()),row.type(),CatalogIdentityOwner.owner(row.type()),p.source(),p.sha256(),p.expiresAt());}
private static LinkView view(Link row){return row==null?null:new LinkView(Long.toString(row.id()),Long.toString(row.registrationId()),Long.toString(row.version()),row.type(),row.owner(),CatalogIdentityOwner.prefix(row.type())+row.sourceId(),row.sourceVersion(),row.sourceCode(),row.sourceName(),row.evidenceSha256(),row.expiresAt(),row.linkedAt(),row.requestId());}
private static String path(long id){return "/api/governance/v1/asset-catalogs/registrations/"+id+"/source-identity";}
}
@@ -0,0 +1,95 @@
package cn.aixunkeji.datagov.governance.assetcatalog;
import cn.aixunkeji.datagov.governance.api.scheduling.GovernanceSchedulingService.*;
import cn.aixunkeji.datagov.governance.scheduling.GovernanceSchedulingDubboService;
import cn.aixunkeji.datagov.governance.scheduling.GovernanceWorkflowOwner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static cn.aixunkeji.datagov.governance.assetcatalog.AssetCatalogApi.*;
/** Registers confirmed inventory evidence through the original catalog command; never publishes. */
@Component
@RequiredArgsConstructor
public class AssetRegistrationWorkflowOwner implements GovernanceWorkflowOwner {
private final AssetCatalogService service;
private final AssetCatalogJdbcRepository repository;
private final AssetCatalogInventorySource inventory;
private final AssetCatalogActorProvider actors;
private final AssetCatalogPolicy policy;
@Override public String type() { return "ASSET_REGISTER"; }
@Override public Binding resolve(Reference reference) { return resolved(reference).binding(); }
@Override public Result execute(Command command) {
var resolved = resolved(command.reference());
if (!command.ownerVersion().equals(resolved.binding().version())
|| !command.ownerSha256().equals(resolved.binding().sha256())) {
return changed();
}
service.catalogFromInventory(command.reference().referenceId(), command.idempotencyKey(), resolved.command(), resolved.sourceSha());
repository.authorize(actors.current(), command.reference().referenceId(), CatalogAction.MAINTAIN);
return success(command.reference().referenceId());
}
@Override public Result observe(Command command, Result prior) {
var actor = actors.current();
long id = command.reference().referenceId();
repository.authorize(actor, id, CatalogAction.VIEW);
var receipt = repository.completedWorkflowRequest(actor, path(id), command.idempotencyKey());
return receipt != null && receipt == id ? success(id) : prior;
}
private Resolved resolved(Reference reference) {
Map<String, String> options = reference.options();
if (options == null || !options.keySet().equals(Set.of("inventoryTaskId", "inventoryCandidateId"))) {
throw AssetCatalogDomainException.validation("资产登记节点须选择盘点任务和已确认候选");
}
long task = positive(options.get("inventoryTaskId"));
long candidate = positive(options.get("inventoryCandidateId"));
var actor = actors.current();
if (actor.actorId() != reference.actorId() || actor.organizationId() != reference.orgId()) {
throw AssetCatalogDomainException.forbidden();
}
repository.authorize(actor, reference.referenceId(), CatalogAction.VIEW);
repository.authorize(actor, reference.referenceId(), CatalogAction.MAINTAIN);
var node = repository.node(reference.referenceId(), actor);
if (node.status() != CatalogStatus.DRAFT && node.status() != CatalogStatus.UNPUBLISHED) {
throw AssetCatalogDomainException.conflict("已发布目录不可自动登记,请先按原流程下架目录");
}
var source = inventory.read(task, candidate, actor);
var command = new InventoryCatalogCommand(task, candidate, source.candidateVersion(), node.version());
// Validate freshness, confirmation, identity and payload before publishing a workflow binding.
var catalogCommand = policy.normalize(source.command(command), LocalDateTime.now());
if (repository.assets(node.catalogId(), actor).stream().anyMatch(asset -> asset.assetRef().equals(catalogCommand.assetRef()))) {
throw AssetCatalogDomainException.conflict("该资产已在目录登记,请使用原登记记录");
}
String hash = GovernanceSchedulingDubboService.hash(List.of(node, source, catalogCommand));
return new Resolved(command, new Binding("AUTHORIZED", Long.toString(node.version()), hash, null),
GovernanceSchedulingDubboService.hash(source));
}
private static long positive(String value) {
if (value == null || !value.matches("[1-9][0-9]{0,18}")) {
throw AssetCatalogDomainException.validation("盘点任务或候选ID无效");
}
try { return Long.parseLong(value); }
catch (NumberFormatException invalid) { throw AssetCatalogDomainException.validation("盘点任务或候选ID无效"); }
}
private static String path(long id) { return "/api/governance/v1/asset-catalogs/" + id + "/inventory-assets"; }
private static Result success(long id) {
return new Result("SUCCEEDED", "/api/governance/v1/asset-catalogs/" + id, null,
"已登记确认的盘点资产,目录发布仍由原流程处理", LocalDateTime.now());
}
private static Result changed() {
return new Result("FAILED", null, "ASSET_REGISTRATION_BINDING_CHANGED", "目录或盘点确认依据已变化,请重新发布流程", LocalDateTime.now());
}
private record Resolved(InventoryCatalogCommand command, Binding binding, String sourceSha) { }
}
@@ -0,0 +1,32 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.stp.StpUtil;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import org.springframework.stereotype.Component;
import java.util.Set;
/** HTTP only. RPC must pass its independently authenticated/delegated Actor to the Service. */
@Component
class AssetComplianceActorProvider {
@org.apache.dubbo.config.annotation.DubboReference(check=false,retries=0)
private cn.aixunkeji.system.api.RemoteUserService users;
AssetComplianceModel.Actor current() {
StpUtil.checkLogin();
Long actor = LoginHelper.getUserId();
Long department = LoginHelper.getDeptId();
if (actor == null || department == null || actor <= 0 || department <= 0) throw new AssetCompliancePolicy.Failure(ErrorCode.UNAUTHENTICATED);
// Matches the existing Governance department-scoped organization boundary (AssetDetailActorProvider).
java.util.Set<String> permissions=new java.util.HashSet<>();
for (String action:java.util.List.of("view","create","update","submit","review")) {
String purpose="COMPLIANCE_"+action.toUpperCase(java.util.Locale.ROOT);
var result=users.resolveAssetActor(actor,department,purpose);
java.time.Instant now=java.time.Instant.now();
if (result==null || result.userId()!=actor || result.deptId()!=department || !purpose.equals(result.purpose())
|| result.checkedAt()==null || result.checkedAt().isBefore(now.minusSeconds(30)) || result.checkedAt().isAfter(now.plusSeconds(2)))
throw new AssetCompliancePolicy.Failure(ErrorCode.UNAUTHENTICATED);
if (result.allowed()) permissions.add("aixun:governance:asset-compliance:"+action);
}
return new AssetComplianceModel.Actor(actor,department,department,permissions);
}
}
@@ -0,0 +1,53 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
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.governance.assetcompliance.AssetComplianceModel.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/governance/v1/asset-compliance")
public class AssetComplianceController {
private final AssetComplianceService service;
public AssetComplianceController(AssetComplianceService service){this.service=service;}
@GetMapping
@SaCheckPermission("aixun:governance:asset-compliance:view")
public R<ReviewPage> list(@RequestParam(required=false) String keyword,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="20") int size){return R.ok(service.list(keyword,page,size));}
@GetMapping("/candidates")
@SaCheckPermission("aixun:governance:asset-compliance:view")
public R<AuthorizedCandidatePage> candidates(@RequestParam(required=false) String keyword,@RequestParam(required=false) String objectType,@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="20") int size){return R.ok(service.candidates(new CandidateQuery(keyword,objectType),page,size));}
@PostMapping("/materials")
@SaCheckPermission("aixun:governance:asset-compliance:view")
public R<ScopeView> materials(@RequestBody ScopeSelection selection){return R.ok(service.scope(selection));}
@GetMapping("/{id}")
@SaCheckPermission("aixun:governance:asset-compliance:view")
public R<ReviewRecord> detail(@PathVariable long id){return R.ok(service.detail(id));}
@PostMapping
@SaCheckPermission("aixun:governance:asset-compliance:create")
@Log(title="合规材料登记",businessType=BusinessType.INSERT,isSaveRequestData=false,isSaveResponseData=false)
public R<ReviewRecord> create(@RequestHeader("Idempotency-Key") String key,@RequestBody SaveCommand command){
if(command.id()!=null) throw AssetComplianceModel.invalid(); return R.ok(service.save(key,command));
}
@PutMapping("/{id}")
@SaCheckPermission("aixun:governance:asset-compliance:update")
@Log(title="合规材料整改",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
public R<ReviewRecord> update(@PathVariable long id,@RequestHeader("Idempotency-Key") String key,@RequestBody SaveCommand command){
if(command.id()==null || command.id()!=id) throw AssetComplianceModel.invalid(); return R.ok(service.save(key,command));
}
@PostMapping("/{id}/submit")
@SaCheckPermission("aixun:governance:asset-compliance:submit")
@Log(title="提交合规审查",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
public R<ReviewRecord> submit(@PathVariable long id,@RequestHeader("Idempotency-Key") String key,@RequestBody ActionCommand command){return R.ok(service.action(id,"SUBMIT",key,command));}
@PostMapping("/{id}/review/{decision}")
@SaCheckPermission("aixun:governance:asset-compliance:review")
@Log(title="合规独立复核",businessType=BusinessType.UPDATE,isSaveRequestData=false,isSaveResponseData=false)
public R<ReviewRecord> review(@PathVariable long id,@PathVariable String decision,@RequestHeader("Idempotency-Key") String key,@RequestBody ActionCommand command){
if(!java.util.Set.of("APPROVE","NEEDS_MATERIAL","REJECT").contains(decision)) throw AssetComplianceModel.invalid();
return R.ok(service.action(id,decision,key,command));
}
@PostMapping("/{id}/verify")
@SaCheckPermission("aixun:governance:asset-compliance:view")
public R<VerificationView> verify(@PathVariable long id){return R.ok(service.verify(id));}
}
@@ -0,0 +1,36 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice(assignableTypes={AssetComplianceController.class,ComplianceAssistController.class})
class AssetComplianceErrorHandler {
@ExceptionHandler(AssetCompliancePolicy.Failure.class)
ResponseEntity<R<Void>> domain(AssetCompliancePolicy.Failure failure){return result(failure.code);}
@ExceptionHandler({IllegalArgumentException.class,HttpMessageNotReadableException.class})
ResponseEntity<R<Void>> invalid(Exception ignored){return result(ErrorCode.INVALID_CONTRACT);}
@ExceptionHandler(DuplicateKeyException.class)
ResponseEntity<R<Void>> duplicate(Exception ignored){return result(ErrorCode.IDEMPOTENCY_CONFLICT);}
@ExceptionHandler(DataAccessException.class)
ResponseEntity<R<Void>> database(Exception ignored){return result(ErrorCode.NOT_CONFIGURED);}
private ResponseEntity<R<Void>> result(ErrorCode code){
String message=switch(code){
case UNAUTHENTICATED->"请重新登录";
case FORBIDDEN->"无权操作该范围、材料不可访问或不允许本人复核提交";
case NOT_FOUND->"审查记录或材料不存在或不可访问";
case VERSION_CONFLICT->"记录已变化,请刷新后重试";
case IDEMPOTENCY_CONFLICT->"请求重复或内容冲突,请刷新记录确认结果";
case SOURCE_CONFLICT->"来源或授权依据已变化,请重新选择范围并补充材料";
case EVIDENCE_EXPIRED->"材料或授权已过期,请补充有效材料";
case NOT_CONFIGURED,OWNER_UNKNOWN->"暂时无法读取审查依据,请稍后重试或联系管理员";
default->"请检查审查范围、材料及必填内容";
};
return ResponseEntity.status(code.httpStatus()).body(R.fail(code.httpStatus(),message));
}
}
@@ -0,0 +1,55 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.function.Function;
@Component
public class AssetComplianceEvidenceResolver {
/** Implemented only by the Integration-owned real Owner adapter. No permissive fallback bean. */
public interface OwnerPort {
AuthorizedCandidatePage candidates(Actor actor, CandidateQuery query, int page, int size);
ResolvedScope resolveScope(Actor actor, ScopeSelection selection);
List<ResolvedMaterial> materials(Actor actor, ResolvedScope scope);
CurrentEvidence revalidate(Actor actor, StoredBinding binding, List<MaterialRef> materialRefs);
}
private final ObjectProvider<OwnerPort> owners;
public AssetComplianceEvidenceResolver(ObjectProvider<OwnerPort> owners) { this.owners = owners; }
private <T> T read(Function<OwnerPort,T> call) {
OwnerPort owner = owners.getIfUnique();
if (owner == null) throw new AssetCompliancePolicy.Failure(ErrorCode.NOT_CONFIGURED);
try {
T result = call.apply(owner);
if (result == null) throw new AssetCompliancePolicy.Failure(ErrorCode.OWNER_UNKNOWN);
return result;
} catch (AssetCompliancePolicy.Failure ex) { throw ex; }
catch (RuntimeException ex) { throw new AssetCompliancePolicy.Failure(ErrorCode.OWNER_UNKNOWN); }
}
AuthorizedCandidatePage candidates(Actor a, CandidateQuery q, int p, int s) {
AssetComplianceModel.pagination(p,s); return read(owner -> owner.candidates(a,q,p,s));
}
ResolvedScope scope(Actor a, ScopeSelection selection) {
ResolvedScope scope = read(owner -> owner.resolveScope(a,selection));
AssetCompliancePolicy.scope(a,scope.binding());
if (!scope.binding().purpose().equals(selection.purposeRef()) || !scope.binding().recipientRef().equals(selection.recipientRef())
|| !scope.binding().fields().equals(selection.fields()) || !scope.requestedExpiresAt().equals(selection.requestedExpiresAt()))
throw new AssetCompliancePolicy.Failure(ErrorCode.SOURCE_CONFLICT);
if (scope.state() != VerificationState.VERIFIED && scope.state() != VerificationState.UNRESOLVED)
throw new AssetCompliancePolicy.Failure(ErrorCode.FORBIDDEN);
if (scope.error() != null && scope.error() != ErrorCode.NOT_CONFIGURED && scope.error() != ErrorCode.OWNER_UNKNOWN)
throw new AssetCompliancePolicy.Failure(scope.error());
return scope;
}
List<ResolvedMaterial> materials(Actor a, ResolvedScope scope) {
return List.copyOf(read(owner -> owner.materials(a,scope)));
}
CurrentEvidence current(Actor a, StoredBinding binding, List<MaterialRef> refs) {
AssetCompliancePolicy.scope(a,binding.binding());
CurrentEvidence evidence = read(owner -> owner.revalidate(a,binding,refs));
if (!binding.binding().equals(evidence.binding())) throw new AssetCompliancePolicy.Failure(ErrorCode.SOURCE_CONFLICT);
return evidence;
}
}
@@ -0,0 +1,105 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.JsonNode;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
/** All writes participate in the caller's transaction, including immutable revisions and idempotency. */
@Repository
class AssetComplianceJdbcRepository {
private final JdbcTemplate jdbc;
private final JsonMapper json;
AssetComplianceJdbcRepository(JdbcTemplate jdbc, JsonMapper json) { this.jdbc=jdbc; this.json=json; }
String encode(Object value) {
try { return json.writeValueAsString(new Envelope(1,value)); }
catch (Exception ex) { throw new AssetCompliancePolicy.Failure(ErrorCode.INVALID_CONTRACT); }
}
private record Envelope(int schemaVersion,Object value) {}
<T> T decode(String value, Class<T> type) {
try {
JsonNode node=json.readTree(value);
if (node.path("schemaVersion").asInt()!=1 || !node.has("value")) throw new IllegalArgumentException();
return json.treeToValue(node.get("value"),type);
} catch (Exception ex) { throw new AssetCompliancePolicy.Failure(ErrorCode.OWNER_UNKNOWN); }
}
String hash(Object value) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(encode(value).getBytes(StandardCharsets.UTF_8))); }
catch (java.security.NoSuchAlgorithmException ex) { throw new IllegalStateException(ex); }
}
ReviewPage list(Actor a,String keyword,int page,int size) {
AssetComplianceModel.pagination(page,size); AssetComplianceModel.optionalText(keyword,200);
String term=keyword==null ? "" : keyword;
Long total=jdbc.queryForObject("SELECT COUNT(*) FROM sec_compliance_review WHERE organization_id=? AND department_id=? AND LOCATE(?,title)>0",Long.class,a.organizationId(),a.departmentId(),term);
List<Long> ids=jdbc.query("SELECT review_id FROM sec_compliance_review WHERE organization_id=? AND department_id=? AND LOCATE(?,title)>0 ORDER BY update_time DESC,review_id DESC LIMIT ? OFFSET ?",
(rs,n)->rs.getLong(1),a.organizationId(),a.departmentId(),term,size,(page-1)*size);
return new ReviewPage(ids.stream().map(id->get(a,id,false)).toList(),total==null?0:total,page,size);
}
ReviewRecord get(Actor a,long id,boolean lock) {
List<ReviewRecord> rows=jdbc.query("SELECT r.*,v.scope_snapshot_json,v.checklist_json FROM sec_compliance_review r JOIN sec_compliance_revision v ON v.review_id=r.review_id AND v.revision_no=r.current_revision AND v.organization_id=r.organization_id AND v.department_id=r.department_id WHERE r.review_id=? AND r.organization_id=? AND r.department_id=?"+(lock?" FOR UPDATE":""),
(rs,n)->map(a,rs),id,a.organizationId(),a.departmentId());
if(rows.size()!=1) throw new AssetCompliancePolicy.Failure(ErrorCode.NOT_FOUND);
return rows.getFirst();
}
private ReviewRecord map(Actor a,ResultSet rs) throws SQLException {
long id=rs.getLong("review_id"), revision=rs.getLong("current_revision");
StoredBinding binding=decode(rs.getString("scope_snapshot_json"),StoredBinding.class);
Checklist checklist=decode(rs.getString("checklist_json"),Checklist.class);
List<ResolvedMaterial> materials=jdbc.query("SELECT binding_json FROM sec_compliance_evidence WHERE review_id=? AND revision_no=? AND organization_id=? AND department_id=? ORDER BY evidence_key_sha256",
(er,n)->decode(er.getString(1),ResolvedMaterial.class),id,revision,a.organizationId(),a.departmentId());
return new ReviewRecord(id,rs.getLong("row_version"),ReviewStatus.valueOf(rs.getString("review_status")),checklist.selection(),binding,
checklist.objectLabel(),checklist.purposeLabel(),checklist.recipientLabel(),materials,checklist.content(),
rs.getObject("submitted_by",Long.class),rs.getObject("reviewed_by",Long.class),checklist.opinion(),time(rs,"create_time"),time(rs,"update_time"),time(rs,"valid_from"),time(rs,"expires_at"));
}
private static Instant time(ResultSet rs,String column)throws SQLException { Timestamp t=rs.getTimestamp(column); return t==null?null:t.toInstant(); }
private static Timestamp ts(Instant time){return time==null?null:Timestamp.from(time);}
Long replay(Actor a,String operation,String object,String key,String payload) {
AssetComplianceModel.text(key); if(key.length()>128) throw AssetComplianceModel.invalid();
String scope=hash(List.of(a.organizationId(),a.departmentId(),a.actorId(),operation,object,key));
List<Long> found=jdbc.query("SELECT * FROM sec_compliance_request WHERE scope_sha256=? AND organization_id=? AND department_id=?",
(rs,n)->{
if(rs.getLong("actor_id")!=a.actorId() || !rs.getString("operation").equals(operation) || !rs.getString("object_id").equals(object)
|| !rs.getString("idempotency_key").equals(key) || !rs.getString("payload_sha256").equals(payload)) throw new AssetCompliancePolicy.Failure(ErrorCode.IDEMPOTENCY_CONFLICT);
return Long.valueOf(rs.getString("response_ref"));
},scope,a.organizationId(),a.departmentId());
return found.isEmpty()?null:found.getFirst();
}
void finish(Actor a,String operation,String object,String key,String payload,ReviewRecord record,String requestId) {
String scope=hash(List.of(a.organizationId(),a.departmentId(),a.actorId(),operation,object,key));
jdbc.update("INSERT INTO sec_compliance_request(request_id,organization_id,department_id,actor_id,operation,object_id,idempotency_key,scope_sha256,payload_sha256,response_ref,response_json,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
requestId,a.organizationId(),a.departmentId(),a.actorId(),operation,object,key,scope,payload,Long.toString(record.id()),encode(record),ts(record.updatedAt()));
}
void persist(Actor a,ReviewRecord old,ReviewRecord r,String action,String payload,String requestId) {
UsageBinding b=r.binding().binding(); long revision=r.version()+1;
if(old==null) {
jdbc.update("INSERT INTO sec_compliance_review(review_id,organization_id,department_id,title,object_owner,object_type,object_id,resource_version,version_kind,content_sha256,purpose,recipient_ref,fields_json,binding_sha256,current_revision,review_status,row_version,submitted_by,reviewed_by,requested_expires_at,valid_from,expires_at,create_by,update_by,create_time,update_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
r.id(),a.organizationId(),a.departmentId(),r.objectLabel().substring(0,Math.min(200,r.objectLabel().length())),b.object().owner(),b.object().objectType(),b.object().objectId(),b.object().resourceVersion(),b.object().versionKind().name(),b.contentSha256(),b.purpose(),b.recipientRef(),encode(b.fields()),hash(b),revision,r.status().name(),r.version(),r.submittedBy(),r.reviewedBy(),ts(r.binding().requestedExpiresAt()),ts(r.validFrom()),ts(r.expiresAt()),a.actorId(),a.actorId(),ts(r.createdAt()),ts(r.updatedAt()));
} else {
int changed=jdbc.update("UPDATE sec_compliance_review SET title=?,object_owner=?,object_type=?,object_id=?,resource_version=?,version_kind=?,content_sha256=?,purpose=?,recipient_ref=?,fields_json=?,binding_sha256=?,current_revision=?,review_status=?,row_version=?,submitted_by=?,reviewed_by=?,submitted_at=CASE WHEN ?='SUBMIT' THEN ? ELSE submitted_at END,reviewed_at=CASE WHEN ? IN ('APPROVE','REJECT','NEEDS_MATERIAL') THEN ? ELSE reviewed_at END,requested_expires_at=?,valid_from=?,expires_at=?,update_by=?,update_time=? WHERE review_id=? AND organization_id=? AND department_id=? AND row_version=?",
r.objectLabel().substring(0,Math.min(200,r.objectLabel().length())),b.object().owner(),b.object().objectType(),b.object().objectId(),b.object().resourceVersion(),b.object().versionKind().name(),b.contentSha256(),b.purpose(),b.recipientRef(),encode(b.fields()),hash(b),revision,r.status().name(),r.version(),r.submittedBy(),r.reviewedBy(),action,ts(r.updatedAt()),action,ts(r.updatedAt()),ts(r.binding().requestedExpiresAt()),ts(r.validFrom()),ts(r.expiresAt()),a.actorId(),ts(r.updatedAt()),r.id(),a.organizationId(),a.departmentId(),old.version());
if(changed!=1) throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);
}
jdbc.update("INSERT INTO sec_compliance_revision(revision_id,review_id,revision_no,organization_id,department_id,action,before_status,after_status,actor_id,opinion,rectification,scope_snapshot_json,checklist_json,source_rights_sha256,material_set_sha256,payload_sha256,valid_from,expires_at,request_id,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
IdGeneratorUtil.nextLongId(),r.id(),revision,a.organizationId(),a.departmentId(),action,old==null?"DRAFT":old.status().name(),r.status().name(),a.actorId(),r.opinion(),r.status()==ReviewStatus.NEEDS_MATERIAL?r.opinion():null,
encode(r.binding()),encode(new Checklist(r.selection(),r.objectLabel(),r.purposeLabel(),r.recipientLabel(),r.content(),r.opinion())),hash(List.of(r.binding().sourceEvidence(),r.binding().authorizationBasis())),hash(r.materials()),payload,ts(r.validFrom()),ts(r.expiresAt()),requestId,ts(r.updatedAt()));
for(ResolvedMaterial m:r.materials()) jdbc.update("INSERT INTO sec_compliance_evidence(evidence_id,review_id,revision_no,organization_id,department_id,evidence_kind,evidence_owner,evidence_ref,evidence_version,evidence_sha256,observed_at,expires_at,binding_json,authorization_version,revocation_ref,evidence_key_sha256) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
IdGeneratorUtil.nextLongId(),r.id(),revision,a.organizationId(),a.departmentId(),m.evidenceKind(),m.reference().owner(),m.reference().reference(),m.reference().version(),m.evidence().sha256(),ts(m.evidence().observedAt()),ts(m.evidence().expiresAt()),encode(m),m.reviewAccessAuthorization().version(),m.reviewAccessRevocation().evidence().reference(),hash(m.reference()));
}
List<ReviewRecord> approved(Actor a,UsageBinding binding) {
List<Long> ids=jdbc.query("SELECT review_id FROM sec_compliance_review WHERE organization_id=? AND department_id=? AND binding_sha256=? AND review_status='APPROVED' AND expires_at>? ORDER BY review_id DESC LIMIT 100",
(rs,n)->rs.getLong(1),a.organizationId(),a.departmentId(),hash(binding),ts(Instant.now()));
return ids.stream().map(id->get(a,id,false)).filter(r->Objects.equals(r.binding().binding(),binding)).toList();
}
}
@@ -0,0 +1,138 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner;
import java.time.Instant;
import java.util.List;
import java.util.Set;
import java.util.Objects;
/** Owner facts and internal review records are intentionally separate. Shape validation is not authorization. */
public final class AssetComplianceModel {
private AssetComplianceModel() {}
public record Actor(long actorId, long organizationId, long departmentId, Set<String> permissions) {
public Actor { positive(actorId); positive(organizationId); positive(departmentId); permissions = Set.copyOf(permissions);
if (permissions.size() > 10000) throw invalid(); permissions.forEach(AssetComplianceModel::text); }
}
public record CandidateQuery(String keyword, String objectType) {
public CandidateQuery { optionalText(keyword, 200); optionalText(objectType, 64); }
}
public record Option(String reference, String label) {
public Option { text(reference); text(label); }
}
public record Candidate(String reference, String label, AssetUpgradeOwner.ObjectVersion object,
String contentSha256, List<Option> purposes, List<Option> recipients, List<Option> fields) {
public Candidate { text(reference); text(label); Objects.requireNonNull(object); optionalSha(contentSha256);
purposes = options(purposes); recipients = options(recipients); fields = options(fields); }
}
public record AuthorizedCandidatePage(List<Candidate> rows, long total, int page, int size) {
public AuthorizedCandidatePage { rows = copy(rows); pagination(page, size); if (total < rows.size() || rows.size() > size) throw invalid(); }
}
public record ScopeSelection(String candidateRef, String purposeRef, String recipientRef,
List<String> fields, Instant requestedExpiresAt) {
public ScopeSelection { text(candidateRef); text(purposeRef); text(recipientRef); fields = normalizedFields(fields); Objects.requireNonNull(requestedExpiresAt); }
}
public record UsageBinding(long organizationId, long departmentId, AssetUpgradeOwner.ObjectVersion object,
String contentSha256, String purpose, String recipientRef, List<String> fields) {
public UsageBinding { positive(organizationId); positive(departmentId); Objects.requireNonNull(object);
optionalText(object.owner(),64); optionalText(object.objectType(),64);
optionalSha(contentSha256); text(purpose); text(recipientRef); fields = normalizedFields(fields); }
}
public enum VerificationState { VERIFIED, UNRESOLVED, REVOKED, EXPIRED, DENIED }
public record EvidenceVersion(String owner, String reference, long version, String sha256, Instant observedAt, Instant expiresAt) {
public EvidenceVersion { text(owner); text(reference); positive(version); sha(sha256); interval(observedAt, expiresAt); }
}
public record RevocationObservation(EvidenceVersion evidence, VerificationState state) {
public RevocationObservation { Objects.requireNonNull(evidence); Objects.requireNonNull(state); }
}
public record AuthorizationBasis(String reference, String grantorRef, String granteeRef, String rightType,
UsageBinding binding, Instant validFrom, Instant validUntil, String restrictions,
EvidenceVersion originalEvidence, RevocationObservation revocation, VerificationState state) {
public AuthorizationBasis { text(reference); Objects.requireNonNull(binding); Objects.requireNonNull(state);
optionalText(grantorRef,512); optionalText(granteeRef,512); optionalText(rightType,512); optionalText(restrictions,4000);
if (validFrom != null && validUntil != null) interval(validFrom,validUntil);
if (state == VerificationState.VERIFIED) { text(grantorRef); text(granteeRef); text(rightType);
interval(validFrom,validUntil); Objects.requireNonNull(originalEvidence); Objects.requireNonNull(revocation); } }
}
public record ResolvedScope(UsageBinding binding, String objectLabel, String purposeLabel, String recipientLabel,
String sourceMembersSha256, List<EvidenceVersion> sourceEvidence,
List<AuthorizationBasis> authorizationBasis, Instant requestedExpiresAt,
VerificationState state, AssetUpgradeOwner.ErrorCode error) {
public ResolvedScope { Objects.requireNonNull(binding); text(objectLabel); text(purposeLabel); text(recipientLabel);
optionalSha(sourceMembersSha256); sourceEvidence = copy(sourceEvidence); authorizationBasis = copy(authorizationBasis);
Objects.requireNonNull(requestedExpiresAt); Objects.requireNonNull(state); if (state == VerificationState.VERIFIED && error != null) throw invalid(); }
}
public record MaterialRef(String owner, String reference, long version) {
public MaterialRef { text(owner); optionalText(owner,64); text(reference); positive(version); }
}
public record PrivateMaterialBinding(String businessOwner, String objectType, String objectId, long objectVersion,
String fileId, String fileVersion, String bytesSha256, long byteLength, String mime, String fileUse) {
public PrivateMaterialBinding { text(businessOwner); text(objectType); text(objectId); positive(objectVersion);
text(fileId); text(fileVersion); sha(bytesSha256); if (byteLength < 0) throw invalid(); text(mime);
if (!Set.of("EVIDENCE", "REGISTRATION_MATERIAL").contains(fileUse)) throw invalid(); }
}
public record ResolvedMaterial(MaterialRef reference, String label, String evidenceKind, UsageBinding scope,
PrivateMaterialBinding file, EvidenceVersion evidence, EvidenceVersion reviewAccessAuthorization,
RevocationObservation reviewAccessRevocation, VerificationState state, AssetUpgradeOwner.ErrorCode error) {
public ResolvedMaterial { Objects.requireNonNull(reference); text(label); text(evidenceKind); optionalText(evidenceKind,32); Objects.requireNonNull(scope);
Objects.requireNonNull(state); if (state == VerificationState.VERIFIED) { Objects.requireNonNull(file);
Objects.requireNonNull(evidence); Objects.requireNonNull(reviewAccessAuthorization); Objects.requireNonNull(reviewAccessRevocation); if (error != null) throw invalid(); } }
}
public record StoredBinding(UsageBinding binding, String sourceMembersSha256, List<EvidenceVersion> sourceEvidence,
List<AuthorizationBasis> authorizationBasis, Instant requestedExpiresAt) {
public StoredBinding { Objects.requireNonNull(binding); optionalSha(sourceMembersSha256); sourceEvidence = copy(sourceEvidence);
authorizationBasis = copy(authorizationBasis); Objects.requireNonNull(requestedExpiresAt); }
}
public record CurrentEvidence(UsageBinding binding, String sourceMembersSha256, List<EvidenceVersion> sourceEvidence,
List<AuthorizationBasis> authorizationBasis, List<ResolvedMaterial> materials,
Instant observedAt, Instant validFrom, Instant expiresAt, VerificationState state, AssetUpgradeOwner.ErrorCode error) {
public CurrentEvidence { Objects.requireNonNull(binding); optionalSha(sourceMembersSha256); sourceEvidence = copy(sourceEvidence);
authorizationBasis = copy(authorizationBasis); materials = copy(materials); Objects.requireNonNull(observedAt);
Objects.requireNonNull(state); if (validFrom != null && expiresAt != null) interval(validFrom, expiresAt);
if (state == VerificationState.VERIFIED) { interval(validFrom, expiresAt); if (error != null) throw invalid(); } }
}
public enum ReviewStatus { DRAFT, SUBMITTED, NEEDS_MATERIAL, APPROVED, REJECTED }
public record ReviewContent(String sourceLegality, String rightsChain, String personalInformation,
String sensitiveInformation, String tradeSecrets, String deliveryRestrictions) {
public ReviewContent { note(sourceLegality); note(rightsChain); note(personalInformation); note(sensitiveInformation); note(tradeSecrets); note(deliveryRestrictions); }
}
public record SaveCommand(Long id, long version, ScopeSelection selection, List<MaterialRef> materials, ReviewContent content) {
public SaveCommand { if (id != null) positive(id); if (version < 0) throw invalid(); Objects.requireNonNull(selection);
materials = copy(materials); if (materials.size() > 100 || materials.stream().distinct().count() != materials.size()) throw invalid(); Objects.requireNonNull(content); }
}
public record ActionCommand(long version, String opinion) {
public ActionCommand { if (version < 0) throw invalid(); note(opinion); }
}
public record ReviewRecord(long id, long version, ReviewStatus status, ScopeSelection selection, StoredBinding binding,
String objectLabel, String purposeLabel, String recipientLabel, List<ResolvedMaterial> materials,
ReviewContent content, Long submittedBy, Long reviewedBy, String opinion,
Instant createdAt, Instant updatedAt, Instant validFrom, Instant expiresAt) {
public ReviewRecord { materials = copy(materials); }
}
public record ReviewPage(List<ReviewRecord> rows, long total, int page, int size) {
public ReviewPage { rows = copy(rows); pagination(page, size); }
}
public record MaterialOption(MaterialRef reference, String label, String evidenceKind, VerificationState state) {}
public record ScopeView(String objectLabel, String purposeLabel, String recipientLabel, VerificationState state, List<MaterialOption> materials) {
public ScopeView { materials = copy(materials); }
}
public record VerificationView(VerificationState state, String message, Instant expiresAt) {}
public record Checklist(ScopeSelection selection, String objectLabel, String purposeLabel, String recipientLabel,
ReviewContent content, String opinion) {}
static <T> List<T> copy(List<T> list) { if (list == null || list.size() > 2000) throw invalid(); return List.copyOf(list); }
static List<Option> options(List<Option> list) {
list=copy(list); if (list.stream().map(Option::reference).distinct().count()!=list.size()) throw invalid(); return list;
}
static List<String> normalizedFields(List<String> fields) {
fields = copy(fields); if (fields.isEmpty() || fields.stream().distinct().count() != fields.size()) throw invalid();
fields.forEach(AssetComplianceModel::text); return fields.stream().sorted().toList();
}
static void positive(long n) { if (n <= 0) throw invalid(); }
static void text(String s) { if (s == null || s.isBlank() || s.length() > 512) throw invalid(); }
static void optionalText(String s, int max) { if (s != null && s.length() > max) throw invalid(); }
static void note(String s) { if (s == null || s.length() > 4000) throw invalid(); }
static void sha(String s) { if (s == null || !s.matches("[a-f0-9]{64}")) throw invalid(); }
static void optionalSha(String s) { if (s != null) sha(s); }
static void interval(Instant from, Instant until) { if (from == null || until == null || !until.isAfter(from)) throw invalid(); }
static void pagination(int page, int size) { if (page < 1 || page > 10000 || size < 1 || size > 100) throw invalid(); }
static IllegalArgumentException invalid() { return new IllegalArgumentException("INVALID_CONTRACT"); }
}
@@ -0,0 +1,112 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.dataproduct.api.assetupgrade.DatasetInputEvidenceOwner;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.stp.StpUtil;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.*;
import static cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
/** DataProduct remains Owner of source, original licence and private material. No cross-domain SQL. */
@Component
public class AssetComplianceOwnerAdapter implements AssetComplianceEvidenceResolver.OwnerPort {
@DubboReference(group=DatasetInputEvidenceOwner.GROUP,version=DatasetInputEvidenceOwner.VERSION,check=false,retries=0)
private DatasetInputEvidenceOwner inputs;
@DubboReference(check=false,retries=0)
private RemoteUserService users;
private DatasetInputEvidenceOwner.Query query(Actor a,String keyword,int page,int size) {
StpUtil.checkLogin();
if (!Boolean.TRUE.equals(SaManager.getConfig().getCheckSameToken()) || !Long.valueOf(a.actorId()).equals(LoginHelper.getUserId())
|| !Long.valueOf(a.departmentId()).equals(LoginHelper.getDeptId()) || a.organizationId()!=a.departmentId()) throw denied();
var d=users.resolveAssetActor(a.actorId(),a.departmentId(),"COMPLIANCE_VIEW");
if (d==null || !d.allowed() || d.userId()!=a.actorId() || d.deptId()!=a.departmentId() || !"COMPLIANCE_VIEW".equals(d.purpose())) throw denied();
return new DatasetInputEvidenceOwner.Query(a.actorId(),a.organizationId(),a.departmentId(),keyword,page,size);
}
private DatasetInputEvidenceOwner.Evidence read(Actor a,String id) {
var e=inputs.resolve(query(a,null,1,1),id);
if (e==null || !id.equals(e.inputId()) || e.organizationId()!=a.organizationId() || e.departmentId()!=a.departmentId()
|| e.observedAt()==null || e.observedAt().isAfter(Instant.now().plusSeconds(2)) || e.observedAt().isBefore(Instant.now().minusSeconds(30))) throw denied();
return e;
}
private AssetUpgradeOwner.ObjectVersion object(DatasetInputEvidenceOwner.Evidence e) {
return new AssetUpgradeOwner.ObjectVersion("dataproduct","DATASET_INPUT",e.inputId(),e.registrationVersion(),AssetUpgradeOwner.VersionKind.DRAFT);
}
@Override public AuthorizedCandidatePage candidates(Actor a,CandidateQuery q,int page,int size) {
if (q.objectType()!=null && !q.objectType().equals("DATASET_INPUT")) return new AuthorizedCandidatePage(List.of(),0,page,size);
var result=inputs.candidates(query(a,q.keyword(),page,size));
var rows=result.items().stream().map(e -> new Candidate(e.inputId(),e.label(),object(e),e.contentSha256(),
List.of(new Option(e.purpose(),"内部标注")),List.of(new Option(e.recipient(),"本部门")),
e.fields().stream().map(f -> new Option(f,f)).toList())).toList();
return new AuthorizedCandidatePage(rows,result.total(),page,size);
}
private VerificationState state(DatasetInputEvidenceOwner.Evidence e) {
return switch(e.originalState()) {
case "VERIFIED" -> e.reviewedBy()!=null && e.reviewedBy()!=e.submittedBy() && e.reviewedAt()!=null
? VerificationState.VERIFIED:VerificationState.UNRESOLVED;
case "REVOKED" -> VerificationState.REVOKED;
case "EXPIRED" -> VerificationState.EXPIRED;
case "REJECTED" -> VerificationState.DENIED;
default -> VerificationState.UNRESOLVED;
};
}
private EvidenceVersion evidence(DatasetInputEvidenceOwner.Evidence e,String reference,long version,String sha) {
return new EvidenceVersion("dataproduct",reference,version,sha,e.observedAt(),e.validUntil());
}
private List<EvidenceVersion> sources(DatasetInputEvidenceOwner.Evidence e) {
if (!e.validUntil().isAfter(e.observedAt())) return List.of();
return List.of(evidence(e,e.sourceRef(),e.registrationVersion()+1,e.sourceSha256()));
}
private List<AuthorizationBasis> basis(DatasetInputEvidenceOwner.Evidence e,UsageBinding b) {
VerificationState state=state(e);
if (!e.validUntil().isAfter(e.observedAt())) return List.of(new AuthorizationBasis("input-license:"+e.inputId(),e.grantor(),e.grantee(),
e.purpose(),b,e.validFrom(),e.validUntil(),e.restrictions(),null,null,VerificationState.EXPIRED));
var original=evidence(e,"original-license:"+e.inputId(),e.registrationVersion()+1,e.evidenceSha256());
return List.of(new AuthorizationBasis("input-license:"+e.inputId(),e.grantor(),e.grantee(),e.purpose(),b,e.validFrom(),e.validUntil(),
e.restrictions(),original,new RevocationObservation(evidence(e,"input-license-state:"+e.inputId(),e.registrationVersion()+1,e.evidenceSha256()),state),state));
}
@Override public ResolvedScope resolveScope(Actor a,ScopeSelection selection) {
var e=read(a,selection.candidateRef());
if (!e.purpose().equals(selection.purposeRef()) || !e.recipient().equals(selection.recipientRef())
|| !e.fields().containsAll(selection.fields()) || selection.requestedExpiresAt().isAfter(e.validUntil())
|| !e.validUntil().isAfter(Instant.now())) throw denied();
var binding=new UsageBinding(a.organizationId(),a.departmentId(),object(e),e.contentSha256(),e.purpose(),e.recipient(),selection.fields());
VerificationState state=state(e);
return new ResolvedScope(binding,e.label(),"内部标注","本部门",e.sourceMembersSha256(),sources(e),basis(e,binding),
selection.requestedExpiresAt(),state==VerificationState.VERIFIED?state:VerificationState.UNRESOLVED,
state==VerificationState.VERIFIED?null:AssetUpgradeOwner.ErrorCode.OWNER_UNKNOWN);
}
private ResolvedMaterial material(DatasetInputEvidenceOwner.Evidence e,UsageBinding b) {
var f=e.material();if (f==null) throw denied();
var reference=new MaterialRef("dataproduct","original-material:"+e.inputId(),f.objectVersion());
var file=new PrivateMaterialBinding(f.businessOwner(),f.objectType(),f.objectId(),f.objectVersion(),f.fileId(),f.fileVersion(),
f.bytesSha256(),f.byteLength(),f.mime(),f.fileUse());
// Expired legal rights do not erase currently authorized access to the historical original.
// Such observations cannot revive usage: the original basis remains EXPIRED above.
Instant materialUntil=e.validUntil().isAfter(e.observedAt())?e.validUntil():e.observedAt().plusSeconds(30);
var observed=new EvidenceVersion("dataproduct",reference.reference(),reference.version(),f.bytesSha256(),e.observedAt(),materialUntil);
var access=new EvidenceVersion("dataproduct",e.reviewAccessRef(),1,e.reviewAccessSha256(),e.observedAt(),materialUntil);
return new ResolvedMaterial(reference,"原始许可材料","ORIGINAL_LICENSE",b,file,observed,access,
new RevocationObservation(access,VerificationState.VERIFIED),VerificationState.VERIFIED,null);
}
@Override public List<ResolvedMaterial> materials(Actor a,ResolvedScope scope) {
var e=read(a,scope.binding().object().objectId());
return List.of(material(e,scope.binding()));
}
@Override public CurrentEvidence revalidate(Actor a,StoredBinding stored,List<MaterialRef> refs) {
var b=stored.binding();
if (!b.object().owner().equals("dataproduct") || !b.object().objectType().equals("DATASET_INPUT")) throw denied();
var e=read(a,b.object().objectId());var item=material(e,b);
if (refs.stream().anyMatch(r -> !r.equals(item.reference()))) throw denied();
boolean same=object(e).equals(b.object()) && Objects.equals(e.contentSha256(),b.contentSha256())
&& e.purpose().equals(b.purpose()) && e.recipient().equals(b.recipientRef()) && e.fields().containsAll(b.fields());
VerificationState state=same?state(e):VerificationState.UNRESOLVED;
return new CurrentEvidence(b,e.sourceMembersSha256(),sources(e),basis(e,b),refs.isEmpty()?List.of():List.of(item),e.observedAt(),
e.validFrom(),e.validUntil(),state,state==VerificationState.VERIFIED?null:AssetUpgradeOwner.ErrorCode.SOURCE_CONFLICT);
}
private static AssetCompliancePolicy.Failure denied() { return new AssetCompliancePolicy.Failure(AssetUpgradeOwner.ErrorCode.FORBIDDEN); }
}
@@ -0,0 +1,99 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
final class AssetCompliancePolicy {
private AssetCompliancePolicy() {}
static final class Failure extends RuntimeException {
final ErrorCode code;
Failure(ErrorCode code) { super(code.name()); this.code = code; }
}
static void permission(Actor actor, String action) {
if (!actor.permissions().contains("*:*:*") && !actor.permissions().contains("aixun:governance:asset-compliance:" + action))
throw new Failure(ErrorCode.FORBIDDEN);
}
static void scope(Actor actor, UsageBinding binding) {
if (actor.organizationId() != binding.organizationId() || actor.departmentId() != binding.departmentId()) throw new Failure(ErrorCode.FORBIDDEN);
}
static boolean fresh(EvidenceVersion e, Instant now) {
return e != null && !e.observedAt().isAfter(now) && e.expiresAt().isAfter(now);
}
static boolean material(ResolvedMaterial m, UsageBinding binding, Instant now) {
return m != null && m.state() == VerificationState.VERIFIED && m.error() == null && binding.equals(m.scope())
&& m.file() != null && fresh(m.evidence(),now) && fresh(m.reviewAccessAuthorization(),now)
&& m.reviewAccessRevocation() != null && m.reviewAccessRevocation().state() == VerificationState.VERIFIED
&& fresh(m.reviewAccessRevocation().evidence(),now)
&& m.reference().owner().equals(m.evidence().owner()) && m.reference().reference().equals(m.evidence().reference())
&& m.reference().version() == m.evidence().version();
}
static void readableMaterials(List<ResolvedMaterial> materials, UsageBinding binding, Instant now) {
if (materials.stream().anyMatch(m -> !material(m,binding,now))) throw new Failure(ErrorCode.FORBIDDEN);
}
static boolean sameEvidence(EvidenceVersion left, EvidenceVersion right) {
return left != null && right != null && left.owner().equals(right.owner()) && left.reference().equals(right.reference())
&& left.version() == right.version() && left.sha256().equals(right.sha256()) && left.expiresAt().equals(right.expiresAt());
}
static boolean sameEvidenceList(List<EvidenceVersion> left, List<EvidenceVersion> right) {
return left.size() == right.size() && left.stream().allMatch(l -> right.stream().filter(r -> sameEvidence(l,r)).count() == 1);
}
static boolean sameBasis(List<AuthorizationBasis> left, List<AuthorizationBasis> right) {
return left.size() == right.size() && left.stream().allMatch(l -> right.stream().filter(r ->
l.reference().equals(r.reference()) && Objects.equals(l.grantorRef(),r.grantorRef()) && Objects.equals(l.granteeRef(),r.granteeRef())
&& Objects.equals(l.rightType(),r.rightType()) && l.binding().equals(r.binding()) && Objects.equals(l.validFrom(),r.validFrom())
&& Objects.equals(l.validUntil(),r.validUntil()) && Objects.equals(l.restrictions(),r.restrictions()) && l.state() == r.state()
&& sameEvidence(l.originalEvidence(),r.originalEvidence()) && l.revocation() != null && r.revocation() != null
&& l.revocation().state() == r.revocation().state() && sameEvidence(l.revocation().evidence(),r.revocation().evidence())).count() == 1);
}
static boolean unchanged(StoredBinding stored, List<ResolvedMaterial> materials, CurrentEvidence current) {
return stored.binding().equals(current.binding()) && Objects.equals(stored.sourceMembersSha256(),current.sourceMembersSha256())
&& sameEvidenceList(stored.sourceEvidence(),current.sourceEvidence()) && sameBasis(stored.authorizationBasis(),current.authorizationBasis())
&& materials.size() == current.materials().size() && materials.stream().allMatch(m -> current.materials().stream().filter(n ->
m.reference().equals(n.reference()) && m.scope().equals(n.scope()) && Objects.equals(m.file(),n.file())
&& m.evidenceKind().equals(n.evidenceKind()) && sameEvidence(m.evidence(),n.evidence())
&& sameEvidence(m.reviewAccessAuthorization(),n.reviewAccessAuthorization())
&& m.reviewAccessRevocation() != null && n.reviewAccessRevocation() != null
&& m.reviewAccessRevocation().state() == n.reviewAccessRevocation().state()
&& sameEvidence(m.reviewAccessRevocation().evidence(),n.reviewAccessRevocation().evidence())).count() == 1);
}
/** Returns the minimum actual validity deadline, never an invented source/content hash. */
static Instant allowUntil(StoredBinding stored, List<ResolvedMaterial> materials, CurrentEvidence current, Instant now) {
if (stored.binding().contentSha256() == null) throw new Failure(ErrorCode.SOURCE_CONFLICT);
return reviewUntil(stored,materials,current,now);
}
/** Internal material review can finish without content bytes; it cannot issue UsageDecision.ALLOW. */
static Instant reviewUntil(StoredBinding stored, List<ResolvedMaterial> materials, CurrentEvidence current, Instant now) {
if (stored.sourceMembersSha256() == null
|| stored.sourceEvidence().isEmpty() || stored.authorizationBasis().isEmpty() || materials.isEmpty()
|| current.state() != VerificationState.VERIFIED || current.error() != null
|| current.observedAt().isAfter(now) || current.validFrom() == null || current.validFrom().isAfter(now)
|| current.expiresAt() == null || !unchanged(stored,materials,current)) throw new Failure(ErrorCode.SOURCE_CONFLICT);
Instant until = earlier(stored.requestedExpiresAt(),current.expiresAt());
for (EvidenceVersion source : current.sourceEvidence()) {
if (!fresh(source,now)) throw new Failure(ErrorCode.EVIDENCE_EXPIRED);
until = earlier(until,source.expiresAt());
}
for (AuthorizationBasis basis : current.authorizationBasis()) {
if (basis.state() != VerificationState.VERIFIED || !basis.binding().equals(current.binding())
|| basis.validFrom() == null || basis.validFrom().isAfter(now) || basis.validUntil() == null
|| !fresh(basis.originalEvidence(),now) || basis.revocation() == null
|| basis.revocation().state() != VerificationState.VERIFIED || !fresh(basis.revocation().evidence(),now))
throw new Failure(ErrorCode.FORBIDDEN);
until = earlier(until,earlier(basis.validUntil(),earlier(basis.originalEvidence().expiresAt(),basis.revocation().evidence().expiresAt())));
}
readableMaterials(current.materials(),current.binding(),now);
for (ResolvedMaterial material : current.materials()) until = earlier(until,earlier(material.evidence().expiresAt(),
earlier(material.reviewAccessAuthorization().expiresAt(),material.reviewAccessRevocation().evidence().expiresAt())));
if (!until.isAfter(now)) throw new Failure(ErrorCode.EVIDENCE_EXPIRED);
return until;
}
static Instant earlier(Instant a, Instant b) { return a.isBefore(b) ? a : b; }
static Instant validFrom(CurrentEvidence current) {
Instant from=current.validFrom();
for (AuthorizationBasis basis:current.authorizationBasis()) if (basis.validFrom().isAfter(from)) from=basis.validFrom();
return from;
}
}
@@ -0,0 +1,154 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import java.util.Objects;
@Service
public class AssetComplianceService {
private final AssetComplianceJdbcRepository repository;
private final AssetComplianceEvidenceResolver resolver;
private final AssetComplianceActorProvider actors;
public AssetComplianceService(AssetComplianceJdbcRepository repository, AssetComplianceEvidenceResolver resolver, AssetComplianceActorProvider actors) {
this.repository=repository; this.resolver=resolver; this.actors=actors;
}
AuthorizedCandidatePage candidates(CandidateQuery query,int page,int size) {
Actor a=actors.current(); AssetCompliancePolicy.permission(a,"view"); return resolver.candidates(a,query,page,size);
}
ScopeView scope(ScopeSelection selection) {
Actor a=actors.current(); AssetCompliancePolicy.permission(a,"view");
ResolvedScope scope=resolver.scope(a,selection);
List<ResolvedMaterial> materials=resolver.materials(a,scope);
return new ScopeView(scope.objectLabel(),scope.purposeLabel(),scope.recipientLabel(),scope.state(),materials.stream()
.filter(m->AssetCompliancePolicy.material(m,scope.binding(),Instant.now()))
.map(m->new MaterialOption(m.reference(),m.label(),m.evidenceKind(),m.state())).toList());
}
ReviewPage list(String keyword,int page,int size) {
Actor a=actors.current(); AssetCompliancePolicy.permission(a,"view");
ReviewPage result=repository.list(a,keyword,page,size);
result.rows().forEach(r->readable(a,r)); return result;
}
ReviewRecord detail(long id) { Actor a=actors.current(); AssetCompliancePolicy.permission(a,"view"); return readable(a,repository.get(a,id,false)); }
private ReviewRecord readable(Actor a,ReviewRecord r) {
AssetCompliancePolicy.scope(a,r.binding().binding());
CurrentEvidence current=resolver.current(a,r.binding(),refs(r));
if(current.error()==ErrorCode.NOT_CONFIGURED || current.error()==ErrorCode.OWNER_UNKNOWN) throw new AssetCompliancePolicy.Failure(current.error());
if(current.state()==VerificationState.DENIED || current.error()==ErrorCode.FORBIDDEN) throw new AssetCompliancePolicy.Failure(ErrorCode.FORBIDDEN);
// Read permission is independent of the approval being reviewed; never query internal APPROVED here.
if(current.materials().size()!=r.materials().size() || !current.materials().stream().map(ResolvedMaterial::reference).toList().containsAll(refs(r)))
throw new AssetCompliancePolicy.Failure(ErrorCode.SOURCE_CONFLICT);
AssetCompliancePolicy.readableMaterials(current.materials(),r.binding().binding(),Instant.now());
return r;
}
private static List<MaterialRef> refs(ReviewRecord r) { return r.materials().stream().map(ResolvedMaterial::reference).toList(); }
@Transactional
public ReviewRecord save(String key,SaveCommand command) {
Actor a=actors.current(); AssetCompliancePolicy.permission(a,command.id()==null?"create":"update");
String object=command.id()==null?"NEW":command.id().toString(), payload=repository.hash(command);
Long replay=repository.replay(a,"SAVE",object,key,payload);
if(replay!=null) return readable(a,repository.get(a,replay,false));
ReviewRecord old=command.id()==null?null:repository.get(a,command.id(),true);
if(old!=null && (old.version()!=command.version() || (old.status()!=ReviewStatus.DRAFT && old.status()!=ReviewStatus.NEEDS_MATERIAL)))
throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);
if(old==null && command.version()!=0) throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);
ResolvedScope scope=resolver.scope(a,command.selection());
Instant now=Instant.now();
if(!scope.requestedExpiresAt().isAfter(now)) throw new AssetCompliancePolicy.Failure(ErrorCode.EVIDENCE_EXPIRED);
List<ResolvedMaterial> available=resolver.materials(a,scope);
List<ResolvedMaterial> selected=command.materials().stream().map(ref -> {
List<ResolvedMaterial> matches=available.stream().filter(m->m.reference().equals(ref)).toList();
if(matches.size()!=1) throw new AssetCompliancePolicy.Failure(ErrorCode.NOT_FOUND); return matches.getFirst();
}).toList();
now=Instant.now();
if(!scope.requestedExpiresAt().isAfter(now)) throw new AssetCompliancePolicy.Failure(ErrorCode.EVIDENCE_EXPIRED);
AssetCompliancePolicy.readableMaterials(selected,scope.binding(),now);
StoredBinding binding=new StoredBinding(scope.binding(),scope.sourceMembersSha256(),scope.sourceEvidence(),scope.authorizationBasis(),scope.requestedExpiresAt());
ReviewRecord result=new ReviewRecord(old==null?IdGeneratorUtil.nextLongId():old.id(),old==null?0:old.version()+1,ReviewStatus.DRAFT,
command.selection(),binding,scope.objectLabel(),scope.purposeLabel(),scope.recipientLabel(),selected,command.content(),null,null,"",
old==null?now:old.createdAt(),now,null,null);
String requestId=UUID.randomUUID().toString();
repository.persist(a,old,result,"SAVE",payload,requestId); repository.finish(a,"SAVE",object,key,payload,result,requestId); return result;
}
@Transactional
public ReviewRecord action(long id,String action,String key,ActionCommand command) {
if(!List.of("SUBMIT","APPROVE","NEEDS_MATERIAL","REJECT").contains(action)) throw AssetComplianceModel.invalid();
Actor a=actors.current(); AssetCompliancePolicy.permission(a,"SUBMIT".equals(action)?"submit":"review");
String payload=repository.hash(command),object=Long.toString(id);
Long replay=repository.replay(a,action,object,key,payload);
if(replay!=null) return readable(a,repository.get(a,replay,false));
ReviewRecord old=repository.get(a,id,true);
if(old.version()!=command.version()) throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);
Instant now=Instant.now(), from=null, until=null; Long submitted=old.submittedBy(),reviewed=null;
ReviewStatus status;
if("SUBMIT".equals(action)) {
if(old.status()!=ReviewStatus.DRAFT && old.status()!=ReviewStatus.NEEDS_MATERIAL) throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);
readable(a,old);
ReviewContent c=old.content();
if(List.of(c.sourceLegality(),c.rightsChain(),c.personalInformation(),c.sensitiveInformation(),c.tradeSecrets(),c.deliveryRestrictions()).stream().anyMatch(String::isBlank))
throw new AssetCompliancePolicy.Failure(ErrorCode.INVALID_CONTRACT);
submitted=a.actorId(); status=ReviewStatus.SUBMITTED;
} else {
if(old.status()!=ReviewStatus.SUBMITTED || old.submittedBy()==null) throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);
if(old.submittedBy()==a.actorId()) throw new AssetCompliancePolicy.Failure(ErrorCode.FORBIDDEN);
if(command.opinion().isBlank()) throw AssetComplianceModel.invalid();
readable(a,old); reviewed=a.actorId();
status=switch(action) { case "APPROVE"->ReviewStatus.APPROVED; case "REJECT"->ReviewStatus.REJECTED; default->ReviewStatus.NEEDS_MATERIAL; };
if(status==ReviewStatus.APPROVED) {
CurrentEvidence current=resolver.current(a,old.binding(),refs(old));
now=Instant.now();
until=AssetCompliancePolicy.reviewUntil(old.binding(),old.materials(),current,now); from=AssetCompliancePolicy.validFrom(current);
}
}
now=Instant.now();
ReviewRecord result=new ReviewRecord(old.id(),old.version()+1,status,old.selection(),old.binding(),old.objectLabel(),old.purposeLabel(),old.recipientLabel(),old.materials(),old.content(),submitted,reviewed,command.opinion(),old.createdAt(),now,from,until);
String requestId=UUID.randomUUID().toString();
repository.persist(a,old,result,action,payload,requestId); repository.finish(a,action,object,key,payload,result,requestId); return result;
}
VerificationView verify(long id) {
Actor a=actors.current(); AssetCompliancePolicy.permission(a,"view"); ReviewRecord r=readable(a,repository.get(a,id,false));
if(r.status()!=ReviewStatus.APPROVED) return new VerificationView(VerificationState.UNRESOLVED,"尚未通过独立复核",null);
if(r.binding().binding().contentSha256()==null) return new VerificationView(VerificationState.UNRESOLVED,"材料已复核,内容版本尚不能核验,暂不可用于发布或交付",null);
try {
Instant until=AssetCompliancePolicy.allowUntil(r.binding(),r.materials(),resolver.current(a,r.binding(),refs(r)),Instant.now());
return new VerificationView(VerificationState.VERIFIED,"当前审查范围有效",until);
} catch(AssetCompliancePolicy.Failure ex) {
return new VerificationView(ex.code==ErrorCode.EVIDENCE_EXPIRED?VerificationState.EXPIRED:VerificationState.UNRESOLVED,"依据已变化、过期或无法核验,请补充材料重新审查",null);
}
}
/** Caller must supply an authenticated/delegated RPC Actor. Context is matched but never authenticates itself. */
public AssetUpgradeOwner.UsageDecision resolveUsage(Actor trustedActor,AssetUpgradeOwner.UsageQuery query) {
try {
Objects.requireNonNull(trustedActor); Objects.requireNonNull(query);
var context=query.context();
if(context.actorId()!=trustedActor.actorId() || context.organizationId()!=trustedActor.organizationId() || context.departmentId()!=trustedActor.departmentId())
throw new AssetCompliancePolicy.Failure(ErrorCode.FORBIDDEN);
AssetCompliancePolicy.permission(trustedActor,"view");
UsageBinding binding=new UsageBinding(context.organizationId(),context.departmentId(),query.object(),query.contentSha256(),query.purpose(),query.recipientRef(),query.fields());
for(ReviewRecord r:repository.approved(trustedActor,binding)) {
try {
if(r.submittedBy()==null || r.reviewedBy()==null || r.submittedBy().equals(r.reviewedBy())) continue;
CurrentEvidence current=resolver.current(trustedActor,r.binding(),refs(r)); Instant now=Instant.now();
Instant until=AssetCompliancePolicy.allowUntil(r.binding(),r.materials(),current,now);
if(r.validFrom()==null || r.validFrom().isAfter(now) || r.expiresAt()==null) continue;
until=AssetCompliancePolicy.earlier(until,r.expiresAt()); if(!until.isAfter(now)) continue;
var evidence=new AssetUpgradeOwner.EvidenceRef("governance",Long.toString(r.id()),r.version()+1,repository.hash(r),now,until);
return new AssetUpgradeOwner.UsageDecision(query,AssetUpgradeOwner.Decision.ALLOW,evidence,null);
} catch(AssetCompliancePolicy.Failure ex) {
if(ex.code==ErrorCode.NOT_CONFIGURED || ex.code==ErrorCode.OWNER_UNKNOWN) throw ex;
}
}
return new AssetUpgradeOwner.UsageDecision(query,AssetUpgradeOwner.Decision.DENY,null,ErrorCode.FORBIDDEN);
} catch(AssetCompliancePolicy.Failure ex) {
return new AssetUpgradeOwner.UsageDecision(query,ex.code==ErrorCode.NOT_CONFIGURED || ex.code==ErrorCode.OWNER_UNKNOWN?AssetUpgradeOwner.Decision.UNKNOWN:AssetUpgradeOwner.Decision.DENY,null,ex.code);
} catch(RuntimeException ex) {
return new AssetUpgradeOwner.UsageDecision(query,AssetUpgradeOwner.Decision.UNKNOWN,null,ErrorCode.OWNER_UNKNOWN);
}
}
}
@@ -0,0 +1,10 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.common.core.domain.R;
import cn.aixunkeji.datagov.governance.api.assetcompliance.ComplianceAssistDirectory.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
@RestController @RequestMapping("/api/governance/v1/asset-compliance/assist")
public class ComplianceAssistController {
private final ComplianceAssistService service;public ComplianceAssistController(ComplianceAssistService service){this.service=service;}
@PostMapping("/context") @SaCheckPermission("aixun:governance:asset-compliance:view") public R<Context> current(@RequestBody Selection selection){return R.ok(service.current(selection));}
}
@@ -0,0 +1,9 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.api.assetcompliance.ComplianceAssistDirectory;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService(version=ComplianceAssistDirectory.VERSION,timeout=30000,retries=0)
public class ComplianceAssistDubboService implements ComplianceAssistDirectory {
private final ComplianceAssistService service;
public ComplianceAssistDubboService(ComplianceAssistService service){this.service=service;}
public Context current(Selection selection){return service.current(selection);}
}
@@ -0,0 +1,58 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.api.assetcompliance.ComplianceAssistDirectory.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import java.time.Instant;
import java.util.*;
import static cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
final class ComplianceAssistPolicy {
static final String NOTE="当前核对仅覆盖所选数据集登记材料的目录、版本和授权状态,未读取或分析材料正文。材料可访问不代表用途已获授权,也不证明六项审查结论;待核事项须人工查阅真实条款并独立复核。";
static Selection selection(Selection raw) {
if(raw==null||raw.scope()==null||raw.materials()==null||raw.materials().size()>100||raw.version()<0
||raw.reviewId()!=null&&raw.reviewId()<1||raw.reviewId()==null&&raw.version()!=0)throw invalid();
var s=scope(raw);var refs=raw.materials().stream().map(m->{if(m==null)throw invalid();return new MaterialRef(m.owner(),m.reference(),m.version());}).toList();
if(new HashSet<>(refs).size()!=refs.size())throw invalid();
var materials=refs.stream().sorted(Comparator.comparing(MaterialRef::owner).thenComparing(MaterialRef::reference).thenComparingLong(MaterialRef::version)).map(m->new Material(m.owner(),m.reference(),m.version())).toList();
return new Selection(raw.reviewId(),raw.version(),new Scope(s.candidateRef(),s.purposeRef(),s.recipientRef(),s.fields(),s.requestedExpiresAt()),materials);
}
static ScopeSelection scope(Selection s){return new ScopeSelection(s.scope().candidateRef(),s.scope().purposeRef(),s.scope().recipientRef(),s.scope().fields(),s.scope().requestedExpiresAt());}
static List<MaterialRef> refs(Selection s){return s.materials().stream().map(m->new MaterialRef(m.owner(),m.reference(),m.version())).toList();}
static void current(Actor actor,Selection selection,ResolvedScope scope,CurrentEvidence current,Instant now){
AssetCompliancePolicy.scope(actor,scope.binding());
if(!"dataproduct".equals(scope.binding().object().owner())||!"DATASET_INPUT".equals(scope.binding().object().objectType())
||!selection.scope().requestedExpiresAt().isAfter(now)||scope.sourceMembersSha256()==null||scope.sourceEvidence().isEmpty())throw conflict();
if(current==null||current.state()==VerificationState.DENIED||current.error()==ErrorCode.FORBIDDEN)throw new AssetCompliancePolicy.Failure(ErrorCode.FORBIDDEN);
if(current.error()==ErrorCode.NOT_CONFIGURED||current.error()==ErrorCode.OWNER_UNKNOWN)throw new AssetCompliancePolicy.Failure(current.error());
if(current.observedAt().isBefore(now.minusSeconds(30))||current.observedAt().isAfter(now.plusSeconds(2)))throw conflict();
var refs=refs(selection);var returned=current.materials().stream().map(ResolvedMaterial::reference).toList();
if(returned.size()!=refs.size()||!new HashSet<>(returned).equals(new HashSet<>(refs)))throw conflict();
var stored=new StoredBinding(scope.binding(),scope.sourceMembersSha256(),scope.sourceEvidence(),scope.authorizationBasis(),scope.requestedExpiresAt());
if(!AssetCompliancePolicy.unchanged(stored,current.materials(),current)||current.sourceEvidence().stream().anyMatch(e->!AssetCompliancePolicy.fresh(e,now)))throw conflict();
AssetCompliancePolicy.readableMaterials(current.materials(),scope.binding(),now);
}
static List<MaterialFact> materials(CurrentEvidence current){
var sorted=current.materials().stream().sorted(Comparator.comparing(m->m.reference().owner()+":"+m.reference().reference()+":"+m.reference().version())).toList();
var result=new ArrayList<MaterialFact>();for(var material:sorted){var until=AssetCompliancePolicy.earlier(material.evidence().expiresAt(),AssetCompliancePolicy.earlier(material.reviewAccessAuthorization().expiresAt(),material.reviewAccessRevocation().evidence().expiresAt()));result.add(new MaterialFact("M"+(result.size()+1),material.label(),material.evidenceKind(),material.reference().version(),material.state().name(),until.toString()));}return List.copyOf(result);
}
static List<AuthorizationFact> authorizations(CurrentEvidence current){var result=new ArrayList<AuthorizationFact>();for(var basis:current.authorizationBasis().stream().sorted(Comparator.comparing(AuthorizationBasis::reference)).toList())result.add(new AuthorizationFact("A"+(result.size()+1),basis.rightType(),basis.state().name(),time(basis.validFrom()),time(basis.validUntil()),basis.restrictions()!=null&&!basis.restrictions().isBlank()));return List.copyOf(result);}
static List<Gap> gaps(CurrentEvidence current,List<MaterialFact> materials,List<AuthorizationFact> authorizations){
var refs=new ArrayList<String>();refs.add("SCOPE");materials.forEach(m->refs.add(m.key()));authorizations.forEach(a->refs.add(a.key()));var evidence=List.copyOf(refs.subList(0,Math.min(refs.size(),20)));
String source=materials.isEmpty()?"尚未选择可供审查的材料;需补充实际来源与取得方式证明。":"已选择材料目录,需查阅原件核实实际来源、取得方式与本次范围是否一致。";
String rights=authorizations.isEmpty()?"当前未返回授权依据,不能确认权利链。":current.state()!=VerificationState.VERIFIED?"当前原始授权尚未确认有效,需按原流程核实授权、复核及撤销状态。":"当前授权状态可核对,但需查阅原条款确认权利链和授权范围。";
return List.of(new Gap("sourceLegality",materials.isEmpty()?"NO_SELECTED_MATERIAL":"SOURCE_TERMS_UNREAD",source,evidence),new Gap("rightsChain",current.state()!=VerificationState.VERIFIED?"AUTHORIZATION_UNCONFIRMED":"RIGHTS_TERMS_UNREAD",rights,evidence),
new Gap("personalInformation","PERSONAL_SCOPE_UNKNOWN","目录信息不包含字段取值或个人信息分类结论,需核实涉及范围、处理依据和必要性。",List.of("SCOPE")),
new Gap("sensitiveInformation","SENSITIVE_SCOPE_UNKNOWN","需核实敏感信息类别、必要措施及适用依据;不能由字段数量推断是否含敏感信息。",List.of("SCOPE")),
new Gap("tradeSecrets","SECRET_SCOPE_UNKNOWN","需由业务责任方核实商业秘密识别与保密要求,材料名称不能证明不存在商业秘密。",evidence),
new Gap("deliveryRestrictions","DELIVERY_TERMS_UNREAD","核对当前用途、申请期限、接收范围与原条款限制,未读取限制条款正文。",evidence));
}
static List<Object> proof(CurrentEvidence current){return Arrays.asList(current.binding(),current.sourceMembersSha256(),current.sourceEvidence().stream().map(ComplianceAssistPolicy::evidence).toList(),
current.authorizationBasis().stream().sorted(Comparator.comparing(AuthorizationBasis::reference)).map(b->Arrays.asList(b.reference(),b.grantorRef(),b.granteeRef(),b.rightType(),b.binding(),b.validFrom(),b.validUntil(),b.restrictions(),b.state(),evidence(b.originalEvidence()),revocation(b.revocation()))).toList(),
current.materials().stream().sorted(Comparator.comparing(m->m.reference().reference())).map(m->Arrays.asList(m.reference(),m.label(),m.evidenceKind(),m.scope(),m.file(),evidence(m.evidence()),evidence(m.reviewAccessAuthorization()),revocation(m.reviewAccessRevocation()))).toList(),current.state(),current.validFrom(),current.expiresAt());}
private static List<Object> evidence(EvidenceVersion e){return e==null?List.of():List.of(e.owner(),e.reference(),e.version(),e.sha256(),e.expiresAt());}
private static List<Object> revocation(RevocationObservation r){return r==null?List.of():List.of(r.state(),evidence(r.evidence()));}
private static String time(Instant value){return value==null?null:value.toString();}
static AssetCompliancePolicy.Failure conflict(){return new AssetCompliancePolicy.Failure(ErrorCode.SOURCE_CONFLICT);}
static IllegalArgumentException invalid(){return new IllegalArgumentException("INVALID_COMPLIANCE_ASSIST_SELECTION");}
private ComplianceAssistPolicy() { }
}
@@ -0,0 +1,27 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
import cn.aixunkeji.datagov.governance.api.assetcompliance.ComplianceAssistDirectory.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
import org.springframework.stereotype.Service;
import tools.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
import static cn.aixunkeji.datagov.governance.assetcompliance.AssetComplianceModel.*;
@Service
class ComplianceAssistService {
private final AssetComplianceActorProvider actors;private final AssetComplianceEvidenceResolver resolver;private final AssetComplianceService reviews;private final ObjectMapper json;
ComplianceAssistService(AssetComplianceActorProvider actors,AssetComplianceEvidenceResolver resolver,AssetComplianceService reviews,ObjectMapper json){this.actors=actors;this.resolver=resolver;this.reviews=reviews;this.json=json;}
Context current(Selection raw){var selection=ComplianceAssistPolicy.selection(raw);var actor=actors.current();AssetCompliancePolicy.permission(actor,"view");var before=read(actor,selection);var after=read(actor,selection);var fresh=actors.current();AssetCompliancePolicy.permission(fresh,"view");if(!actor.equals(fresh)||!before.equals(after))throw ComplianceAssistPolicy.conflict();return before;}
private Context read(Actor actor,Selection selection){
if(selection.reviewId()!=null){var saved=reviews.detail(selection.reviewId());if(saved.version()!=selection.version()||saved.status()!=ReviewStatus.DRAFT&&saved.status()!=ReviewStatus.NEEDS_MATERIAL)throw new AssetCompliancePolicy.Failure(ErrorCode.VERSION_CONFLICT);}
var scope=resolver.scope(actor,ComplianceAssistPolicy.scope(selection));var binding=new StoredBinding(scope.binding(),scope.sourceMembersSha256(),scope.sourceEvidence(),scope.authorizationBasis(),scope.requestedExpiresAt());
var current=resolver.current(actor,binding,ComplianceAssistPolicy.refs(selection));ComplianceAssistPolicy.current(actor,selection,scope,current,Instant.now());
var materials=ComplianceAssistPolicy.materials(current);var authorizations=ComplianceAssistPolicy.authorizations(current);var gaps=ComplianceAssistPolicy.gaps(current,materials,authorizations);
String fingerprint=hash(Arrays.asList(selection,actor.actorId(),actor.organizationId(),actor.departmentId(),actor.permissions().stream().sorted().toList(),scope.objectLabel(),scope.purposeLabel(),ComplianceAssistPolicy.proof(current)));
return new Context(selection,scope.objectLabel(),scope.purposeLabel(),scope.binding().fields().size(),current.state().name(),materials,authorizations,gaps,ComplianceAssistPolicy.NOTE,fingerprint);
}
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 impossible){throw new IllegalStateException(impossible);}}
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.governance.assetcompliance;
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 P35OwnerContext implements PageAssistContextReader {
private final AssetComplianceService service;
@Override public String pageId(){return "P35";}
@Override public Snapshot read(Request r){
qualifiers(r);var v=service.detail(numeric(r));
return snapshot(r,v.version(),"status",v.status(),"version",v.version(),"updatedAt",v.updatedAt(),"materials.length",v.materials().size());
}
}
@@ -0,0 +1,31 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.stereotype.Component;
import java.util.Set;
@Component
class AssetDetailActorProvider {
Actor current() {
var workflow = cn.aixunkeji.datagov.governance.scheduling.WorkflowExecutionContext.current();
if (workflow != null && "ASSET_UPDATE".equals(workflow.type())) {
return new Actor(workflow.actorId(), workflow.orgId(), workflow.orgId(),
Set.of("aixun:governance:asset-detail:view", "aixun:governance:asset-detail:update"));
}
Long actorId = LoginHelper.getUserId();
Long departmentId = LoginHelper.getDeptId();
if (actorId == null || departmentId == null || actorId <= 0 || departmentId <= 0) {
throw AssetDetailDomainException.forbidden();
}
return new Actor(actorId, departmentId, departmentId, Set.copyOf(StpUtil.getPermissionList()));
}
record Actor(long actorId, long organizationId, long departmentId, Set<String> permissions) {
boolean administrator() {
return permissions.contains("aixun:governance:asset-detail:status")
|| permissions.contains("*:*:*");
}
}
}
@@ -0,0 +1,74 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import java.time.LocalDateTime;
import java.util.List;
final class AssetDetailApi {
private AssetDetailApi() { }
enum AssetStatus { DRAFT, ACTIVE, DEPRECATED, ARCHIVED }
enum SectionType { DEFINITION, SCHEMA, SOURCE, LINEAGE, QUALITY, SECURITY, USAGE }
enum EvidenceState { KNOWN, UNKNOWN }
enum OwnerType { OWNER, STEWARD, BUSINESS_OWNER, TECHNICAL_OWNER }
enum SubjectType { USER, ROLE, ORGANIZATION, DEPARTMENT }
enum GovernanceType { STANDARD, QUALITY, SECURITY, COMPLIANCE, CERTIFICATION, REMEDIATION }
enum RelationType { METRIC, TERM, MODEL, TASK, PRODUCT, APPLICATION }
enum CandidateAvailability { AVAILABLE, UNAVAILABLE }
record SectionCommand(SectionType sectionType, String sourceType, String sourceRef,
LocalDateTime observedAt, boolean reliable, String payloadSha256,
String value) { }
record CreateCommand(String assetRef, String assetFqn, String entityId,
List<SectionCommand> sections) { }
record SnapshotCommand(List<SectionCommand> sections, Long version) { }
record OwnerCommand(OwnerType ownerType, SubjectType subjectType, String subjectRef,
LocalDateTime effectiveFrom, LocalDateTime effectiveTo,
String reason, Long version) { }
record GovernanceCommand(GovernanceType governanceType, String evidenceRef,
LocalDateTime observedAt, boolean reliable,
String evidenceSha256, String value, Long version) { }
record RelationCommand(RelationType relationType, String targetRef, String evidenceRef,
LocalDateTime observedAt, boolean reliable,
String evidenceSha256, String reason, Long version) { }
record StatusCommand(AssetStatus targetStatus, String reason, Long version) { }
record AssetView(long assetDetailId, String assetRef, String assetFqn, String entityId,
AssetStatus status, long organizationId, long departmentId, long version,
LocalDateTime createTime, LocalDateTime updateTime) { }
record SectionView(long sectionSnapshotId, long assetDetailId, long snapshotVersion,
SectionType sectionType, String sourceType, String sourceRef,
LocalDateTime observedAt, boolean reliable, String payloadSha256,
EvidenceState evidenceState, String value, LocalDateTime createTime) { }
record OwnerView(long ownerRecordId, long assetDetailId, OwnerType ownerType,
SubjectType subjectType, String subjectRef, LocalDateTime effectiveFrom,
LocalDateTime effectiveTo, String reason, long version,
LocalDateTime createTime) { }
record GovernanceView(long governanceRecordId, long assetDetailId,
GovernanceType governanceType, String evidenceRef,
LocalDateTime observedAt, boolean reliable, String evidenceSha256,
EvidenceState evidenceState, String value, long version,
LocalDateTime createTime) { }
record RelationView(long relationRecordId, long assetDetailId, RelationType relationType,
String targetRef, String evidenceRef, LocalDateTime observedAt,
String evidenceSha256, String reason, long actorId,
LocalDateTime createTime) { }
record TrajectoryView(long trajectoryId, long assetDetailId, String actionType,
String beforeStatus, String afterStatus, String requestId,
long actorId, String summary, LocalDateTime createTime) { }
record DetailView(AssetView asset, List<SectionView> sections, List<OwnerView> owners,
List<GovernanceView> governance, List<RelationView> relations,
List<TrajectoryView> trajectories) { }
record SourceCandidate(String entityId, String assetRef, String assetFqn, String name,
String displayName, LocalDateTime observedAt) { }
record SourceCandidatePage(List<SourceCandidate> items, String before, String after) { }
record SourceCandidateDetail(SourceCandidate source, List<SectionCommand> sections) { }
record GovernanceCandidate(GovernanceType governanceType, String label,
GovernanceCommand command) { }
record RelationCandidate(RelationType relationType, String targetRef, String label,
String evidenceRef, LocalDateTime observedAt,
String evidenceSha256, String reason) { }
record RelationCandidatePage(RelationType relationType, CandidateAvailability availability,
String message, List<RelationCandidate> items,
String before, String after) { }
record WriteView<T>(String requestId, T result) { }
}
@@ -0,0 +1,32 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.datagov.governance.api.metadatacatalog.MetadataCatalogAdapterService;
import cn.aixunkeji.datagov.governance.api.metadatalineage.MetadataLineageAdapterService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;
@Component
class AssetDetailCandidateGateway {
@org.springframework.beans.factory.annotation.Autowired(required=false)
private cn.aixunkeji.datagov.governance.nativemetadata.MetadataBackendRoutes routes;
@DubboReference(version = MetadataCatalogAdapterService.VERSION, group = MetadataCatalogAdapterService.GROUP,
url = "dubbo://integration:20880", timeout = MetadataCatalogAdapterService.MAX_TIMEOUT_MILLIS,
retries = 0, check = false, injvm = false)
private MetadataCatalogAdapterService catalog;
@DubboReference(version = MetadataLineageAdapterService.VERSION, group = MetadataLineageAdapterService.GROUP,
url = "dubbo://integration:20880", timeout = MetadataLineageAdapterService.MAX_TIMEOUT_MILLIS,
retries = 0, check = false, injvm = false)
private MetadataLineageAdapterService lineage;
MetadataCatalogAdapterService catalog() {
if (catalog == null) throw AssetDetailDomainException.unavailable("来源候选暂不可用");
return routes==null ? catalog : routes.catalog(catalog);
}
MetadataLineageAdapterService lineage() {
if (lineage == null) throw AssetDetailDomainException.unavailable("来源候选暂不可用");
return routes==null ? lineage : routes.lineage(lineage);
}
}
@@ -0,0 +1,415 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.datagov.governance.api.metadatacatalog.MetadataCatalogAdapterService;
import cn.aixunkeji.datagov.governance.api.metadatalineage.MetadataLineageAdapterService;
import cn.aixunkeji.datagov.governance.assetdetail.AssetDetailApi.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Supplier;
import java.util.regex.Pattern;
@Service
@RequiredArgsConstructor
@Slf4j
class AssetDetailCandidateService {
static final int MAX_PAGE_SIZE = 50;
private static final int MAX_SOURCE_PAGES = 10;
private static final int MAX_SOURCE_ITEMS = 500;
static final int MAX_PAYLOAD_LENGTH = 8_192;
private static final Pattern SHA256 = Pattern.compile("[a-f0-9]{64}");
private static final Set<RelationType> UNAVAILABLE_RELATIONS =
EnumSet.of(RelationType.METRIC, RelationType.MODEL, RelationType.PRODUCT);
private final AssetDetailCandidateGateway gateway;
private final AssetDetailJdbcRepository repository;
private final AssetDetailActorProvider actorProvider;
private final JsonMapper mapper;
SourceCandidatePage sourceCandidates(int rawLimit, String after, String keyword) {
int limit = limit(rawLimit);
String cursor = optional(after, 512, "分页游标");
String term = optional(keyword, 100, "候选关键词");
LocalDateTime now = LocalDateTime.now();
List<SourceCandidate> items = new ArrayList<>(limit);
String firstBefore = null;
String lastAfter = null;
int consumed = 0;
int eligible = 0;
int pages = 0;
boolean complete = false;
try {
for (int pageNumber = 0; pageNumber < MAX_SOURCE_PAGES && items.size() < limit; pageNumber++) {
int remaining = limit - items.size();
String requestCursor = cursor;
MetadataCatalogAdapterService.CatalogPage page = external(() -> gateway.catalog().page(
new MetadataCatalogAdapterService.PageQuery(MetadataCatalogAdapterService.EntityType.TABLE,
remaining, requestCursor, term, null, null, null)));
pages++;
if (page == null || page.items() == null || page.items().size() > remaining) malformed();
if (pageNumber == 0) firstBefore = boundedCursor(page.before());
consumed += page.items().size();
if (consumed > MAX_SOURCE_ITEMS) malformed();
// A bad entry must not invalidate a valid entry on the same external page.
List<MetadataCatalogAdapterService.CatalogItem> eligibleItems = page.items().stream()
.filter(item -> eligibleSource(item, now)).toList();
eligible += eligibleItems.size();
items.addAll(eligibleItems.stream().map(item -> source(item, now)).toList());
lastAfter = boundedCursor(page.after());
if (items.size() >= limit || lastAfter == null) {
complete = true;
break;
}
if (page.items().isEmpty() || lastAfter.equals(requestCursor)) malformed();
cursor = lastAfter;
}
if (!complete) malformed();
log.info("Asset source candidates; stage={}, limit={}, keywordPresent={}, afterPresent={}, pages={}, consumed={}, eligible={}, returned={}, cursorPresent={}, outcome={}",
"SOURCE_CANDIDATES", limit, term != null, after != null, pages, consumed, eligible, items.size(), lastAfter != null, "SUCCESS");
return new SourceCandidatePage(items, firstBefore, lastAfter);
} catch (AssetDetailDomainException exception) {
log.warn("Asset source candidates failed; stage={}, limit={}, keywordPresent={}, afterPresent={}, pages={}, consumed={}, eligible={}, outcome={}, errorCode={}",
"SOURCE_CANDIDATES", limit, term != null, after != null, pages, consumed, eligible, "UNAVAILABLE", exception.code());
throw exception;
}
}
SourceCandidateDetail sourceCandidate(String rawEntityId) {
String entityId = required(rawEntityId, 512, "来源实体ID");
LocalDateTime now = LocalDateTime.now();
MetadataCatalogAdapterService.CatalogDetail detail = external(() -> gateway.catalog().detail(
new MetadataCatalogAdapterService.DetailQuery(MetadataCatalogAdapterService.EntityType.TABLE, entityId)));
MetadataLineageAdapterService.LineageGraph lineage = external(() -> gateway.lineage().lineage(
new MetadataLineageAdapterService.LineageQuery(MetadataLineageAdapterService.EntityType.TABLE,
entityId, 1, 1)));
if (detail == null || detail.item() == null || lineage == null) malformed();
SourceCandidate source = source(detail.item(), now);
if (!source.entityId().equals(entityId)) malformed();
List<SectionCommand> sections = List.of(
definition(detail, source, now), schema(detail, source, now), source(detail, source, now),
lineage(lineage, source, now), unknown(SectionType.QUALITY, source, source.observedAt()),
security(detail, source, now), usage(detail, source, now));
return new SourceCandidateDetail(source, sections);
}
List<GovernanceCandidate> governanceCandidates(long rawAssetDetailId) {
long assetDetailId = positive(rawAssetDetailId);
var actor = actorProvider.current();
DetailView detail = repository.detail(assetDetailId, actor);
LocalDateTime now = LocalDateTime.now();
EnumMap<GovernanceType, GovernanceView> latest = new EnumMap<>(GovernanceType.class);
for (GovernanceView item : detail.governance()) {
if (reliable(item.evidenceState(), item.reliable(), item.observedAt(), item.evidenceSha256(),
item.value(), now)) latest.put(item.governanceType(), item);
}
return latest.values().stream().sorted(Comparator.comparing(GovernanceView::governanceType))
.map(item -> new GovernanceCandidate(item.governanceType(), governanceLabel(item.governanceType()),
new GovernanceCommand(item.governanceType(), item.evidenceRef(), item.observedAt(), true,
item.evidenceSha256(), item.value(), detail.asset().version())))
.toList();
}
RelationCandidatePage relationCandidates(long rawAssetDetailId, RelationType relationType,
int rawLimit, String after, String keyword) {
long assetDetailId = positive(rawAssetDetailId);
var actor = actorProvider.current();
repository.asset(assetDetailId, actor);
if (relationType == null) throw AssetDetailDomainException.validation("关联类型不能为空");
if (UNAVAILABLE_RELATIONS.contains(relationType)) {
return new RelationCandidatePage(relationType, CandidateAvailability.UNAVAILABLE,
"当前类型暂无可验证候选", List.of(), null, null);
}
int limit = limit(rawLimit);
String cursor = optional(after, 512, "分页游标");
String term = optional(keyword, 100, "候选关键词");
return relationType == RelationType.TERM
? termCandidates(limit, cursor, term)
: lineageCandidates(relationType, limit, cursor, term);
}
private RelationCandidatePage termCandidates(int limit, String after, String keyword) {
LocalDateTime observedAt = LocalDateTime.now();
var page = external(() -> gateway.catalog().candidates(new MetadataCatalogAdapterService.CandidateQuery(
MetadataCatalogAdapterService.CandidateKind.GLOSSARY_TERM, limit, after, keyword)));
if (page == null || page.items() == null || page.items().size() > limit) malformed();
List<RelationCandidate> items = page.items().stream().map(item -> {
if (item == null) malformed();
String id = required(item.externalId(), 512, "术语候选ID");
String label = label(item.displayName(), item.name(), item.fullyQualifiedName());
String target = "glossary-term:" + id;
String evidence = "catalog:glossary-term:" + id;
return relation(RelationType.TERM, target, label, evidence, observedAt, "关联术语");
}).toList();
return new RelationCandidatePage(RelationType.TERM, CandidateAvailability.AVAILABLE, null,
items, boundedCursor(page.before()), boundedCursor(page.after()));
}
private RelationCandidatePage lineageCandidates(RelationType relationType, int limit,
String after, String keyword) {
MetadataLineageAdapterService.EntityType entityType = relationType == RelationType.TASK
? MetadataLineageAdapterService.EntityType.PIPELINE
: MetadataLineageAdapterService.EntityType.DASHBOARD;
var page = external(() -> gateway.lineage().candidates(
new MetadataLineageAdapterService.CandidateQuery(entityType, limit, after, keyword)));
if (page == null || page.items() == null || page.items().size() > limit) malformed();
LocalDateTime now = LocalDateTime.now();
List<RelationCandidate> items = page.items().stream().map(item -> {
if (item == null) malformed();
String id = required(item.externalId(), 512, "关联候选ID");
if (item.entityType() != entityType || !fresh(item.updatedAt(), now)) malformed();
String prefix = relationType == RelationType.TASK ? "pipeline:" : "dashboard:";
String evidencePrefix = relationType == RelationType.TASK ? "lineage:pipeline:" : "lineage:dashboard:";
return relation(relationType, prefix + id,
label(item.displayName(), item.name(), item.fullyQualifiedName()),
evidencePrefix + id, item.updatedAt(), relationType == RelationType.TASK ? "关联任务" : "关联应用");
}).toList();
return new RelationCandidatePage(relationType, CandidateAvailability.AVAILABLE, null,
items, boundedCursor(page.before()), boundedCursor(page.after()));
}
private SourceCandidate source(MetadataCatalogAdapterService.CatalogItem item, LocalDateTime now) {
if (item == null || item.entityType() != MetadataCatalogAdapterService.EntityType.TABLE
|| !validSourceTime(item.updatedAt(), now)) malformed();
return new SourceCandidate(required(item.externalId(), 512, "TABLE实体ID"),
"table:" + required(item.externalId(), 512, "TABLE实体ID"),
required(item.fullyQualifiedName(), 512, "TABLE FQN"), required(item.name(), 256, "TABLE名称"),
label(item.displayName(), item.name(), item.fullyQualifiedName()), item.updatedAt());
}
static boolean eligibleSource(MetadataCatalogAdapterService.CatalogItem item, LocalDateTime now) {
if (item == null || item.entityType() != MetadataCatalogAdapterService.EntityType.TABLE
|| !validSourceTime(item.updatedAt(), now)) return false;
return bounded(item.externalId(), 512) && bounded(item.fullyQualifiedName(), 512)
&& bounded(item.name(), 256) && bounded(firstNonBlank(item.displayName(), item.name(), item.fullyQualifiedName()), 256);
}
// Catalog updatedAt is the last metadata change, not an expiry of the table identity.
// Evidence sections still use fresh() and retain the original observation time.
private static boolean validSourceTime(LocalDateTime updatedAt, LocalDateTime now) {
return updatedAt != null && !updatedAt.isAfter(now.plusMinutes(5));
}
private static boolean bounded(String value, int max) {
return !blank(value) && value.trim().length() <= max;
}
private SectionCommand definition(MetadataCatalogAdapterService.CatalogDetail detail,
SourceCandidate source, LocalDateTime now) {
String description = firstNonBlank(detail.business() == null ? null : detail.business().description(),
detail.item().description());
if (description == null || !fresh(source.observedAt(), now)) return unknown(SectionType.DEFINITION, source, source.observedAt());
return known(SectionType.DEFINITION, source, source.observedAt(), Map.of("description", description));
}
private SectionCommand schema(MetadataCatalogAdapterService.CatalogDetail detail,
SourceCandidate source, LocalDateTime now) {
var technical = detail.technical();
if (technical == null || technical.fields() == null || technical.fields().isEmpty()
|| technical.fields().size() > 200 || !fresh(source.observedAt(), now)) {
return unknown(SectionType.SCHEMA, source, source.observedAt());
}
List<Map<String, Object>> fields = technical.fields().stream().map(field -> {
if (field == null || blank(field.name()) || blank(field.dataType())) malformed();
Map<String, Object> fieldPayload = new TreeMap<>();
fieldPayload.put("constraint", value(field.constraint())); fieldPayload.put("dataLength", field.dataLength());
fieldPayload.put("dataType", field.dataType()); fieldPayload.put("description", value(field.description()));
fieldPayload.put("nullable",field.nullable());
fieldPayload.put("name", field.name()); return fieldPayload;
}).sorted(Comparator.comparing(item -> String.valueOf(item.get("name")))).toList();
Map<String, Object> payload = new TreeMap<>();
payload.put("fields", fields); payload.put("partitionColumns", sorted(technical.partitionColumns(), 200));
payload.put("tableType", value(technical.tableType())); payload.put("constraints", sorted(technical.constraints(), 200));
return known(SectionType.SCHEMA, source, source.observedAt(), payload);
}
private SectionCommand source(MetadataCatalogAdapterService.CatalogDetail detail,
SourceCandidate source, LocalDateTime now) {
var item = detail.item();
if (!reference(item.service()) || !reference(item.database()) || !reference(item.schema())
|| !fresh(source.observedAt(), now)) return unknown(SectionType.SOURCE, source, source.observedAt());
Map<String, Object> payload = new TreeMap<>();
payload.put("database", referencePayload(item.database())); payload.put("schema", referencePayload(item.schema()));
payload.put("service", referencePayload(item.service())); payload.put("tableFqn", source.assetFqn());
return known(SectionType.SOURCE, source, source.observedAt(), payload);
}
private SectionCommand lineage(MetadataLineageAdapterService.LineageGraph graph,
SourceCandidate source, LocalDateTime now) {
if (graph.root() == null || !source.entityId().equals(graph.root().externalId()) || graph.truncated()
|| !fresh(graph.observedAt(), now) || graph.nodes() == null || graph.upstreamEdges() == null
|| graph.downstreamEdges() == null || graph.fieldMappings() == null
|| graph.nodes().size() > MetadataLineageAdapterService.MAX_NODES
|| graph.upstreamEdges().size() + graph.downstreamEdges().size() > MetadataLineageAdapterService.MAX_EDGES
|| graph.fieldMappings().size() > MetadataLineageAdapterService.MAX_FIELD_MAPPINGS) {
return unknown(SectionType.LINEAGE, source, graph.observedAt());
}
Map<String, Object> payload = new TreeMap<>();
payload.put("nodes", nodes(graph.nodes()));
payload.put("upstreamEdges", edges(graph.upstreamEdges()));
payload.put("downstreamEdges", edges(graph.downstreamEdges()));
payload.put("fieldMappings", fieldMappings(graph.fieldMappings()));
return known(SectionType.LINEAGE, source, graph.observedAt(), payload);
}
private SectionCommand security(MetadataCatalogAdapterService.CatalogDetail detail,
SourceCandidate source, LocalDateTime now) {
var management = detail.management();
if (management == null || management.securityTags() == null || management.securityTags().isEmpty()
|| management.securityTags().size() > 100 || !fresh(source.observedAt(), now)) {
return unknown(SectionType.SECURITY, source, source.observedAt());
}
List<String> tags = management.securityTags().stream().map(tag -> {
if (tag == null || blank(tag.fullyQualifiedName())) malformed();
return tag.fullyQualifiedName();
}).sorted().toList();
return known(SectionType.SECURITY, source, source.observedAt(), Map.of("securityTags", tags));
}
private SectionCommand usage(MetadataCatalogAdapterService.CatalogDetail detail,
SourceCandidate source, LocalDateTime now) {
var operational = detail.operational();
var usage = operational == null ? null : operational.usage();
LocalDateTime observedAt = operational == null ? null : operational.updatedAt();
if (usage == null || !fresh(observedAt, now) || (usage.dailyCount() == null && usage.weeklyCount() == null
&& usage.monthlyCount() == null && usage.percentileRank() == null)) {
return unknown(SectionType.USAGE, source, observedAt);
}
Map<String, Object> payload = new TreeMap<>();
payload.put("dailyCount", usage.dailyCount()); payload.put("monthlyCount", usage.monthlyCount());
payload.put("percentileRank", usage.percentileRank()); payload.put("weeklyCount", usage.weeklyCount());
return known(SectionType.USAGE, source, observedAt, payload);
}
private SectionCommand known(SectionType type, SourceCandidate source, LocalDateTime observedAt, Object payload) {
String body = canonical(payload);
return new SectionCommand(type, "OPENMETADATA_TABLE", source.assetRef(), observedAt, true, sha256(body), body);
}
private SectionCommand unknown(SectionType type, SourceCandidate source, LocalDateTime observedAt) {
return new SectionCommand(type, "OPENMETADATA_TABLE", source.assetRef(), observedAt, false, sha256(""), null);
}
private RelationCandidate relation(RelationType type, String target, String label, String evidence,
LocalDateTime observedAt, String reason) {
String payload = canonical(new TreeMap<>(Map.of("evidenceRef", evidence, "observedAt", observedAt.toString(),
"relationType", type.name(), "targetRef", target)));
return new RelationCandidate(type, target, label, evidence, observedAt, sha256(payload), reason);
}
private String canonical(Object value) {
try {
String payload = mapper.writeValueAsString(value);
if (payload.length() > MAX_PAYLOAD_LENGTH) throw AssetDetailDomainException.unavailable("候选载荷超过限制");
return payload;
} catch (JacksonException exception) {
throw AssetDetailDomainException.unavailable("候选载荷暂不可用");
}
}
private static boolean reliable(EvidenceState state, boolean reliable, LocalDateTime observedAt,
String sha, String value, LocalDateTime now) {
return state == EvidenceState.KNOWN && reliable && fresh(observedAt, now) && sha != null
&& SHA256.matcher(sha).matches() && !blank(value) && sha256(value).equals(sha);
}
private static boolean fresh(LocalDateTime observedAt, LocalDateTime now) {
return observedAt != null && !observedAt.isAfter(now.plusMinutes(5)) && !observedAt.isBefore(now.minusHours(24));
}
private static boolean reference(MetadataCatalogAdapterService.Reference value) {
return value != null && !blank(value.externalId()) && !blank(value.fullyQualifiedName());
}
private static Map<String, Object> referencePayload(MetadataCatalogAdapterService.Reference value) {
Map<String, Object> result = new TreeMap<>();
result.put("externalId", value.externalId()); result.put("fullyQualifiedName", value.fullyQualifiedName());
result.put("name", AssetDetailCandidateService.value(value.name())); result.put("type", AssetDetailCandidateService.value(value.type()));
return result;
}
private static List<String> edges(List<MetadataLineageAdapterService.LineageEdge> values) {
List<String> result = new ArrayList<>();
for (var item : values) {
if (item == null || blank(item.fromExternalId()) || blank(item.toExternalId())) malformed();
result.add(item.fromExternalId() + "|" + item.toExternalId());
}
return result.stream().sorted().toList();
}
private static List<String> nodes(List<MetadataLineageAdapterService.LineageNode> values) {
List<String> result = new ArrayList<>();
for (var item : values) {
if (item == null || item.entityType() == null || blank(item.externalId())) malformed();
result.add(item.externalId() + "|" + item.entityType() + "|" + value(item.fullyQualifiedName()));
}
return result.stream().sorted().toList();
}
private static List<String> fieldMappings(List<MetadataLineageAdapterService.FieldMapping> values) {
List<String> result = new ArrayList<>();
for (var item : values) {
if (item == null || blank(item.fromExternalId()) || blank(item.toExternalId())
|| blank(item.fromField()) || blank(item.toField())) malformed();
result.add(item.fromExternalId() + "|" + item.fromField() + "|" + item.toExternalId() + "|" + item.toField());
}
return result.stream().sorted().toList();
}
private static List<String> sorted(List<String> values, int max) {
if (values == null) return List.of();
if (values.size() > max) malformed();
return values.stream().filter(Objects::nonNull).sorted().toList();
}
private static int limit(int value) {
if (value < 1 || value > MAX_PAGE_SIZE) throw AssetDetailDomainException.validation("候选分页大小无效");
return value;
}
private static long positive(long value) {
if (value <= 0) throw AssetDetailDomainException.validation("资产详情ID无效");
return value;
}
private static String optional(String value, int max, String label) {
if (value == null || value.isBlank()) return null;
return required(value, max, label);
}
private static String boundedCursor(String value) {
return optional(value, 512, "分页游标");
}
private static String required(String value, int max, String label) {
if (blank(value)) throw AssetDetailDomainException.unavailable(label + "缺失");
String normalized = value.trim();
if (normalized.length() > max) throw AssetDetailDomainException.unavailable(label + "超过限制");
return normalized;
}
private static String label(String displayName, String name, String fqn) {
String result = firstNonBlank(displayName, name, fqn);
return required(result, 256, "候选名称");
}
private static String firstNonBlank(String... values) {
for (String value : values) if (!blank(value)) return value.trim();
return null;
}
private static String governanceLabel(GovernanceType type) {
return switch (type) {
case STANDARD -> "标准"; case QUALITY -> "质量"; case SECURITY -> "安全";
case COMPLIANCE -> "合规"; case CERTIFICATION -> "认证"; case REMEDIATION -> "整改";
};
}
private static String value(String value) { return value == null ? "" : value; }
private static boolean blank(String value) { return value == null || value.isBlank(); }
private static void malformed() { throw AssetDetailDomainException.unavailable("候选响应不完整"); }
static <T> T external(Supplier<T> call) {
try { return call.get(); }
catch (AssetDetailDomainException exception) { throw exception; }
catch (RuntimeException exception) { throw AssetDetailDomainException.unavailable("候选服务暂不可用"); }
}
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,112 @@
package cn.aixunkeji.datagov.governance.assetdetail;
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.governance.assetdetail.AssetDetailApi.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/governance/v1/asset-details")
public class AssetDetailController {
private final AssetDetailService service;
private final AssetDetailCandidateService candidateService;
@SaCheckPermission("aixun:governance:asset-detail:view")
@GetMapping
public R<List<AssetView>> list() { return R.ok(service.list()); }
@SaCheckPermission("aixun:governance:asset-detail:view")
@GetMapping("/{assetDetailId}")
public R<DetailView> detail(@PathVariable long assetDetailId) {
return R.ok(service.detail(assetDetailId));
}
@SaCheckPermission("aixun:governance:asset-detail:view")
@GetMapping("/candidates/sources")
public R<SourceCandidatePage> sourceCandidates(@RequestParam(defaultValue = "20") int limit,
@RequestParam(required = false) String after,
@RequestParam(required = false) String keyword) {
return R.ok(candidateService.sourceCandidates(limit, after, keyword));
}
@SaCheckPermission("aixun:governance:asset-detail:view")
@GetMapping("/candidates/sources/{entityId}")
public R<SourceCandidateDetail> sourceCandidate(@PathVariable String entityId) {
return R.ok(candidateService.sourceCandidate(entityId));
}
@SaCheckPermission("aixun:governance:asset-detail:view")
@GetMapping("/{assetDetailId}/candidates/governance")
public R<List<GovernanceCandidate>> governanceCandidates(@PathVariable long assetDetailId) {
return R.ok(candidateService.governanceCandidates(assetDetailId));
}
@SaCheckPermission("aixun:governance:asset-detail:view")
@GetMapping("/{assetDetailId}/candidates/relations")
public R<RelationCandidatePage> relationCandidates(@PathVariable long assetDetailId,
@RequestParam RelationType relationType,
@RequestParam(defaultValue = "20") int limit,
@RequestParam(required = false) String after,
@RequestParam(required = false) String keyword) {
return R.ok(candidateService.relationCandidates(assetDetailId, relationType, limit, after, keyword));
}
@Log(title = "资产详情创建", businessType = BusinessType.INSERT, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-detail:create")
@PostMapping
public R<WriteView<DetailView>> create(@RequestHeader("Idempotency-Key") String key,
@RequestBody CreateCommand command) {
return R.ok(service.create(key, command));
}
@Log(title = "资产详情快照", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-detail:update")
@PostMapping("/{assetDetailId}/snapshots")
public R<WriteView<DetailView>> snapshot(@PathVariable long assetDetailId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody SnapshotCommand command) {
return R.ok(service.snapshot(assetDetailId, key, command));
}
@Log(title = "资产责任归属", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-detail:owner")
@PostMapping("/{assetDetailId}/owners")
public R<WriteView<DetailView>> owner(@PathVariable long assetDetailId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody OwnerCommand command) {
return R.ok(service.owner(assetDetailId, key, command));
}
@Log(title = "资产治理状态", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-detail:governance")
@PostMapping("/{assetDetailId}/governance")
public R<WriteView<DetailView>> governance(@PathVariable long assetDetailId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody GovernanceCommand command) {
return R.ok(service.governance(assetDetailId, key, command));
}
@Log(title = "资产关联对象", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-detail:relation")
@PostMapping("/{assetDetailId}/relations")
public R<WriteView<DetailView>> relation(@PathVariable long assetDetailId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody RelationCommand command) {
return R.ok(service.relation(assetDetailId, key, command));
}
@Log(title = "资产详情状态", businessType = BusinessType.UPDATE, isSaveRequestData = false, isSaveResponseData = false)
@SaCheckPermission("aixun:governance:asset-detail:status")
@PostMapping("/{assetDetailId}/status")
public R<WriteView<DetailView>> status(@PathVariable long assetDetailId,
@RequestHeader("Idempotency-Key") String key,
@RequestBody StatusCommand command) {
return R.ok(service.status(assetDetailId, key, command));
}
}
@@ -0,0 +1,34 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import org.springframework.http.HttpStatus;
final class AssetDetailDomainException extends RuntimeException {
static final int VALIDATION_CODE = 136201;
static final int FORBIDDEN_CODE = 136203;
static final int NOT_FOUND_CODE = 136204;
static final int CONFLICT_CODE = 136209;
static final int UNAVAILABLE_CODE = 136503;
private final int code;
private final HttpStatus status;
private AssetDetailDomainException(int code, HttpStatus status, String message) {
super(message); this.code = code; this.status = status;
}
static AssetDetailDomainException validation(String message) {
return new AssetDetailDomainException(VALIDATION_CODE, HttpStatus.BAD_REQUEST, message);
}
static AssetDetailDomainException forbidden() {
return new AssetDetailDomainException(FORBIDDEN_CODE, HttpStatus.FORBIDDEN, "无权访问资产详情资源");
}
static AssetDetailDomainException notFound() {
return new AssetDetailDomainException(NOT_FOUND_CODE, HttpStatus.NOT_FOUND, "资产详情资源不存在");
}
static AssetDetailDomainException conflict(String message) {
return new AssetDetailDomainException(CONFLICT_CODE, HttpStatus.CONFLICT, message);
}
static AssetDetailDomainException unavailable(String message) {
return new AssetDetailDomainException(UNAVAILABLE_CODE, HttpStatus.SERVICE_UNAVAILABLE, message);
}
int code() { return code; }
HttpStatus status() { return status; }
}
@@ -0,0 +1,14 @@
package cn.aixunkeji.datagov.governance.assetdetail;
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 = AssetDetailController.class)
class AssetDetailExceptionHandler {
@ExceptionHandler(AssetDetailDomainException.class)
ResponseEntity<R<Void>> handle(AssetDetailDomainException exception) {
return ResponseEntity.status(exception.status()).body(R.fail(exception.code(), exception.getMessage()));
}
}
@@ -0,0 +1,29 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import org.springframework.stereotype.Component;
import java.time.ZoneOffset;
import static cn.aixunkeji.datagov.governance.assetidentity.AssetIdentityModel.*;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.AssetState;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode;
/** Local scoped read of the original Owner; never interprets metadata owners as permissions. */
@Component
public class AssetDetailIdentityBridge {
private final AssetDetailJdbcRepository repository;
public AssetDetailIdentityBridge(AssetDetailJdbcRepository repository) { this.repository = repository; }
public DetailFacts read(Actor actor, long id) {
actor.require("aixun:governance:asset-detail:view");
AssetDetailApi.DetailView view;
try { view = repository.detail(id, new AssetDetailActorProvider.Actor(actor.actorId(),
actor.scope().organizationId(), actor.scope().departmentId(), actor.permissions())); }
catch (AssetDetailDomainException rejected) {
throw failure(rejected.code()==AssetDetailDomainException.NOT_FOUND_CODE ? ErrorCode.NOT_FOUND : ErrorCode.OWNER_UNKNOWN);
}
var row = view.asset();
return new DetailFacts(new LegacyAsset(Kind.DETAIL, row.assetDetailId(), row.assetRef(),
new Scope(row.organizationId(), row.departmentId()), row.version(), 0, AssetState.valueOf(row.status().name())),
row.entityId(), row.assetFqn(), view.owners().stream().map(r -> new Responsibility(r.ownerType().name(),
r.subjectType().name(), r.subjectRef(), r.effectiveFrom() == null ? null : r.effectiveFrom().toInstant(ZoneOffset.UTC),
r.effectiveTo() == null ? null : r.effectiveTo().toInstant(ZoneOffset.UTC))).toList());
}
}
@@ -0,0 +1,199 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.common.mybatis.utils.IdGeneratorUtil;
import cn.aixunkeji.datagov.governance.assetdetail.AssetDetailApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
@Repository
@RequiredArgsConstructor
class AssetDetailJdbcRepository {
private static final String ASSET_COLUMNS = "asset_detail_id,asset_ref,asset_fqn,entity_id,asset_status,organization_id,department_id,version,create_time,update_time";
private final JdbcTemplate jdbc;
List<AssetView> list(AssetDetailActorProvider.Actor actor) {
return jdbc.query("SELECT " + ASSET_COLUMNS + " FROM asset_detail_asset WHERE organization_id=? AND department_id=? AND del_flag='0' ORDER BY asset_detail_id DESC",
this::mapAsset, actor.organizationId(), actor.departmentId());
}
AssetView asset(long id, AssetDetailActorProvider.Actor actor) {
return jdbc.query("SELECT " + ASSET_COLUMNS + " FROM asset_detail_asset WHERE asset_detail_id=? AND organization_id=? AND department_id=? AND del_flag='0'",
this::mapAsset, id, actor.organizationId(), actor.departmentId()).stream()
.findFirst().orElseThrow(AssetDetailDomainException::notFound);
}
DetailView detail(long id, AssetDetailActorProvider.Actor actor) {
AssetView asset = asset(id, actor);
return new DetailView(asset, sections(id), owners(id), governance(id), relations(id), trajectories(id));
}
long create(AssetDetailActorProvider.Actor actor, CreateCommand command) {
long id = IdGeneratorUtil.nextLongId();
try {
jdbc.update("INSERT INTO asset_detail_asset(asset_detail_id,asset_ref,asset_fqn,entity_id,asset_status,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,'DRAFT',?,?,?,?,NOW(),?,NOW(),'0',0)",
id, command.assetRef(), command.assetFqn(), command.entityId(), actor.organizationId(),
actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
} catch (DuplicateKeyException exception) {
throw AssetDetailDomainException.conflict("同一组织范围资产详情已存在");
}
appendSections(actor, id, 1L, command.sections());
return id;
}
void snapshot(AssetDetailActorProvider.Actor actor, long id, SnapshotCommand command) {
required(jdbc.update("UPDATE asset_detail_asset SET update_by=?,update_time=NOW(),version=version+1 WHERE asset_detail_id=? AND organization_id=? AND department_id=? AND asset_status<>'ARCHIVED' AND version=? AND del_flag='0'",
actor.actorId(), id, actor.organizationId(), actor.departmentId(), command.version()),
"资产版本已变化或已归档");
Long maximum = jdbc.queryForObject("SELECT COALESCE(MAX(snapshot_version),0) FROM asset_detail_section_snapshot WHERE asset_detail_id=?", Long.class, id);
appendSections(actor, id, (maximum == null ? 0 : maximum) + 1, command.sections());
}
void owner(AssetDetailActorProvider.Actor actor, long id, OwnerCommand command) {
asset(id, actor);
Long overlap = jdbc.queryForObject("SELECT COUNT(*) FROM asset_detail_owner WHERE asset_detail_id=? AND owner_type=? AND effective_from < COALESCE(?, '9999-12-31 23:59:59') AND COALESCE(effective_to, '9999-12-31 23:59:59') > ? AND del_flag='0'",
Long.class, id, command.ownerType().name(), command.effectiveTo(), command.effectiveFrom());
if (overlap != null && overlap > 0) throw AssetDetailDomainException.conflict("责任归属有效期重叠");
bump(actor, id, command.version());
jdbc.update("INSERT INTO asset_detail_owner(owner_record_id,asset_detail_id,owner_type,subject_type,subject_ref,effective_from,effective_to,change_reason,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)",
IdGeneratorUtil.nextLongId(), id, command.ownerType().name(), command.subjectType().name(),
command.subjectRef(), command.effectiveFrom(), command.effectiveTo(), command.reason(),
actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId(), actor.actorId());
}
void governance(AssetDetailActorProvider.Actor actor, long id, GovernanceCommand command) {
bump(actor, id, command.version());
jdbc.update("INSERT INTO asset_detail_governance(governance_record_id,asset_detail_id,governance_type,evidence_ref,observed_at,reliable_flag,evidence_sha256,evidence_state,governance_value,actor_id,organization_id,department_id,create_dept,create_by,create_time,update_by,update_time,del_flag,version) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW(),?,NOW(),'0',0)",
IdGeneratorUtil.nextLongId(), id, command.governanceType().name(), command.evidenceRef(),
command.observedAt(), command.reliable() ? "1" : "0", command.evidenceSha256(),
command.reliable() ? EvidenceState.KNOWN.name() : EvidenceState.UNKNOWN.name(), command.value(),
actor.actorId(), actor.organizationId(), actor.departmentId(), actor.departmentId(),
actor.actorId(), actor.actorId());
}
void relation(AssetDetailActorProvider.Actor actor, long id, RelationCommand command) {
bump(actor, id, command.version());
try {
jdbc.update("INSERT INTO asset_detail_relation(relation_record_id,asset_detail_id,relation_type,target_ref,evidence_ref,observed_at,evidence_sha256,relation_reason,actor_id,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())",
IdGeneratorUtil.nextLongId(), id, command.relationType().name(), command.targetRef(),
command.evidenceRef(), command.observedAt(), command.evidenceSha256(), command.reason(),
actor.actorId(), actor.organizationId(), actor.departmentId(), actor.departmentId(), actor.actorId());
} catch (DuplicateKeyException exception) {
throw AssetDetailDomainException.conflict("关联对象已存在,禁止重复关联");
}
}
void status(AssetDetailActorProvider.Actor actor, long id, AssetStatus current, StatusCommand command) {
required(jdbc.update("UPDATE asset_detail_asset SET asset_status=?,update_by=?,update_time=NOW(),version=version+1 WHERE asset_detail_id=? AND organization_id=? AND department_id=? AND asset_status=? AND version=? AND del_flag='0'",
command.targetStatus().name(), actor.actorId(), id, actor.organizationId(), actor.departmentId(),
current.name(), command.version()), "资产状态或版本已变化");
}
void trajectory(AssetDetailActorProvider.Actor actor, long id, String action, String before,
String after, String requestId, String summary) {
jdbc.update("INSERT INTO asset_detail_trajectory(trajectory_id,asset_detail_id,action_type,before_status,after_status,request_id,actor_id,summary,organization_id,department_id,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,NOW())",
IdGeneratorUtil.nextLongId(), id, action, before, after, requestId, actor.actorId(), summary,
actor.organizationId(), actor.departmentId());
}
Long completedWorkflowRequest(AssetDetailActorProvider.Actor actor, String path, String key) {
return jdbc.query("SELECT response_id FROM asset_detail_request WHERE actor_id=? AND organization_id=? AND department_id=? AND request_method='POST' AND request_path=? AND idempotency_key=? AND request_status='COMPLETED' AND response_id IS NOT NULL",
(rs, row) -> rs.getLong(1), actor.actorId(), actor.organizationId(), actor.departmentId(), path, key)
.stream().findFirst().orElse(null);
}
RequestTicket begin(AssetDetailActorProvider.Actor actor, String method, String path,
String key, String hash) {
List<RequestTicket> found = jdbc.query("SELECT request_id,request_sha256,response_id FROM asset_detail_request WHERE actor_id=? AND request_method=? AND request_path=? AND idempotency_key=?",
(rs, row) -> new RequestTicket(rs.getString(1), rs.getString(2), rs.getObject(3, Long.class)),
actor.actorId(), method, path, key);
if (!found.isEmpty()) {
RequestTicket ticket = found.getFirst();
if (!ticket.hash().equals(hash)) throw AssetDetailDomainException.conflict("同一Idempotency-Key载荷不一致");
if (ticket.responseId() == null) throw AssetDetailDomainException.conflict("同一幂等请求正在处理或已失败");
return ticket;
}
String requestId = "ADR-" + IdGeneratorUtil.nextLongId();
jdbc.update("INSERT INTO asset_detail_request(request_record_id,request_id,actor_id,request_method,request_path,idempotency_key,request_sha256,request_status,organization_id,department_id,create_time) VALUES(?,?,?,?,?,?,?,'PROCESSING',?,?,NOW())",
IdGeneratorUtil.nextLongId(), requestId, actor.actorId(), method, path, key, hash,
actor.organizationId(), actor.departmentId());
return new RequestTicket(requestId, hash, null);
}
void complete(AssetDetailActorProvider.Actor actor, String method, String path,
String key, long responseId) {
required(jdbc.update("UPDATE asset_detail_request SET request_status='COMPLETED',response_id=?,update_time=NOW(),version=version+1 WHERE actor_id=? AND request_method=? AND request_path=? AND idempotency_key=? AND request_status='PROCESSING'",
responseId, actor.actorId(), method, path, key), "幂等请求状态已变化");
}
void fail(AssetDetailActorProvider.Actor actor, String method, String path, String key) {
jdbc.update("UPDATE asset_detail_request SET request_status='FAILED',update_time=NOW(),version=version+1 WHERE actor_id=? AND request_method=? AND request_path=? AND idempotency_key=? AND request_status='PROCESSING'",
actor.actorId(), method, path, key);
}
private void appendSections(AssetDetailActorProvider.Actor actor, long id, long snapshotVersion,
List<SectionCommand> sections) {
for (SectionCommand section : sections) {
jdbc.update("INSERT INTO asset_detail_section_snapshot(section_snapshot_id,asset_detail_id,snapshot_version,section_type,source_type,source_ref,observed_at,reliable_flag,payload_sha256,evidence_state,section_value,actor_id,organization_id,department_id,create_dept,create_by,create_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())",
IdGeneratorUtil.nextLongId(), id, snapshotVersion, section.sectionType().name(),
section.sourceType(), section.sourceRef(), section.observedAt(), section.reliable() ? "1" : "0",
section.payloadSha256(), section.reliable() ? EvidenceState.KNOWN.name() : EvidenceState.UNKNOWN.name(),
section.value(), actor.actorId(), actor.organizationId(), actor.departmentId(),
actor.departmentId(), actor.actorId());
}
}
private void bump(AssetDetailActorProvider.Actor actor, long id, long version) {
required(jdbc.update("UPDATE asset_detail_asset SET update_by=?,update_time=NOW(),version=version+1 WHERE asset_detail_id=? AND organization_id=? AND department_id=? AND asset_status<>'ARCHIVED' AND version=? AND del_flag='0'",
actor.actorId(), id, actor.organizationId(), actor.departmentId(), version),
"资产版本已变化或已归档");
}
private List<SectionView> sections(long id) {
return jdbc.query("SELECT section_snapshot_id,asset_detail_id,snapshot_version,section_type,source_type,source_ref,observed_at,reliable_flag,payload_sha256,evidence_state,section_value,create_time FROM asset_detail_section_snapshot WHERE asset_detail_id=? ORDER BY snapshot_version DESC,section_type",
this::mapSection, id);
}
private List<OwnerView> owners(long id) {
return jdbc.query("SELECT owner_record_id,asset_detail_id,owner_type,subject_type,subject_ref,effective_from,effective_to,change_reason,version,create_time FROM asset_detail_owner WHERE asset_detail_id=? AND del_flag='0' ORDER BY owner_record_id",
this::mapOwner, id);
}
private List<GovernanceView> governance(long id) {
return jdbc.query("SELECT governance_record_id,asset_detail_id,governance_type,evidence_ref,observed_at,reliable_flag,evidence_sha256,evidence_state,governance_value,version,create_time FROM asset_detail_governance WHERE asset_detail_id=? AND del_flag='0' ORDER BY governance_record_id",
this::mapGovernance, id);
}
private List<RelationView> relations(long id) {
return jdbc.query("SELECT relation_record_id,asset_detail_id,relation_type,target_ref,evidence_ref,observed_at,evidence_sha256,relation_reason,actor_id,create_time FROM asset_detail_relation WHERE asset_detail_id=? ORDER BY relation_record_id",
this::mapRelation, id);
}
private List<TrajectoryView> trajectories(long id) {
return jdbc.query("SELECT trajectory_id,asset_detail_id,action_type,before_status,after_status,request_id,actor_id,summary,create_time FROM asset_detail_trajectory WHERE asset_detail_id=? ORDER BY trajectory_id",
(rs, row) -> new TrajectoryView(rs.getLong(1), rs.getLong(2), rs.getString(3),
rs.getString(4), rs.getString(5), rs.getString(6), rs.getLong(7), rs.getString(8),
rs.getTimestamp(9).toLocalDateTime()), id);
}
private AssetView mapAsset(ResultSet rs, int row) throws SQLException {
return new AssetView(rs.getLong(1), rs.getString(2), rs.getString(3), rs.getString(4),
AssetStatus.valueOf(rs.getString(5)), rs.getLong(6), rs.getLong(7), rs.getLong(8),
rs.getTimestamp(9).toLocalDateTime(), rs.getTimestamp(10).toLocalDateTime());
}
private SectionView mapSection(ResultSet rs, int row) throws SQLException {
return new SectionView(rs.getLong(1), rs.getLong(2), rs.getLong(3), SectionType.valueOf(rs.getString(4)),
rs.getString(5), rs.getString(6), nullableTime(rs, 7), "1".equals(rs.getString(8)),
rs.getString(9), EvidenceState.valueOf(rs.getString(10)), rs.getString(11),
rs.getTimestamp(12).toLocalDateTime());
}
private OwnerView mapOwner(ResultSet rs, int row) throws SQLException {
return new OwnerView(rs.getLong(1), rs.getLong(2), OwnerType.valueOf(rs.getString(3)),
SubjectType.valueOf(rs.getString(4)), rs.getString(5), rs.getTimestamp(6).toLocalDateTime(),
nullableTime(rs, 7), rs.getString(8), rs.getLong(9), rs.getTimestamp(10).toLocalDateTime());
}
private GovernanceView mapGovernance(ResultSet rs, int row) throws SQLException {
return new GovernanceView(rs.getLong(1), rs.getLong(2), GovernanceType.valueOf(rs.getString(3)),
rs.getString(4), nullableTime(rs, 5), "1".equals(rs.getString(6)), rs.getString(7),
EvidenceState.valueOf(rs.getString(8)), rs.getString(9), rs.getLong(10),
rs.getTimestamp(11).toLocalDateTime());
}
private RelationView mapRelation(ResultSet rs, int row) throws SQLException {
return new RelationView(rs.getLong(1), rs.getLong(2), RelationType.valueOf(rs.getString(3)),
rs.getString(4), rs.getString(5), rs.getTimestamp(6).toLocalDateTime(), rs.getString(7),
rs.getString(8), rs.getLong(9), rs.getTimestamp(10).toLocalDateTime());
}
private static LocalDateTime nullableTime(ResultSet rs, int index) throws SQLException {
return rs.getTimestamp(index) == null ? null : rs.getTimestamp(index).toLocalDateTime();
}
private static void required(int changed, String message) {
if (changed != 1) throw AssetDetailDomainException.conflict(message);
}
record RequestTicket(String requestId, String hash, Long responseId) { }
}
@@ -0,0 +1,149 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.datagov.governance.assetdetail.AssetDetailApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.json.JsonMapper;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Pattern;
@Component
@RequiredArgsConstructor
class AssetDetailPolicy {
static final int MAX_SECTION_VALUE = 8_192;
private static final Pattern IDEMPOTENCY = Pattern.compile("[A-Za-z0-9._:-]{16,128}");
private static final Pattern SAFE_REF = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.:/@-]{0,511}");
private static final Pattern SHA256 = Pattern.compile("[a-fA-F0-9]{64}");
private static final Pattern DANGEROUS = Pattern.compile("(?is).*(\\b(SELECT|INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|CALL|EXEC|SCRIPT|SHELL)\\b|https?://|jdbc:|password|secret|token|credential|\\.\\./|\\\\).*");
private final JsonMapper mapper;
String idempotencyKey(String value) {
if (value == null || value.isBlank()) throw AssetDetailDomainException.validation("Idempotency-Key不能为空");
String normalized = value.trim();
if (!IDEMPOTENCY.matcher(normalized).matches()) throw AssetDetailDomainException.validation("Idempotency-Key格式无效");
return normalized;
}
CreateCommand normalize(CreateCommand value, LocalDateTime now) {
if (value == null) throw AssetDetailDomainException.validation("资产详情请求不能为空");
return new CreateCommand(safeRef(value.assetRef(), "资产引用"), safeRef(value.assetFqn(), "资产FQN"),
safeRef(value.entityId(), "元数据实体ID"), sections(value.sections(), now));
}
SnapshotCommand normalize(SnapshotCommand value, LocalDateTime now) {
version(value == null ? null : value.version());
return new SnapshotCommand(sections(value.sections(), now), value.version());
}
OwnerCommand normalize(OwnerCommand value, LocalDateTime now) {
if (value == null || value.ownerType() == null || value.subjectType() == null) {
throw AssetDetailDomainException.validation("责任归属请求不完整");
}
version(value.version());
LocalDateTime from = value.effectiveFrom() == null ? now : value.effectiveFrom();
if (value.effectiveTo() != null && !value.effectiveTo().isAfter(from)) {
throw AssetDetailDomainException.validation("责任有效期无效");
}
return new OwnerCommand(value.ownerType(), value.subjectType(), safeRef(value.subjectRef(), "RCP6主体引用"),
from, value.effectiveTo(), required(value.reason(), "责任调整原因", 500), value.version());
}
GovernanceCommand normalize(GovernanceCommand value, LocalDateTime now) {
if (value == null || value.governanceType() == null) throw AssetDetailDomainException.validation("治理状态请求不完整");
version(value.version());
String ref = safeRef(value.evidenceRef(), "治理证据引用");
String sha = sha(value.evidenceSha256(), "治理证据SHA");
EvidenceState state = evidenceState(value.observedAt(), value.reliable(), now);
String body = state == EvidenceState.KNOWN ? required(value.value(), "治理状态值", 1_000) : null;
return new GovernanceCommand(value.governanceType(), ref, value.observedAt(), state == EvidenceState.KNOWN,
sha, body, value.version());
}
RelationCommand normalize(RelationCommand value, String assetRef, LocalDateTime now) {
if (value == null || value.relationType() == null) throw AssetDetailDomainException.validation("关联对象请求不完整");
version(value.version());
String target = safeRef(value.targetRef(), "关联对象引用");
if (target.equals(assetRef)) throw AssetDetailDomainException.conflict("资产关联不能自环");
if (evidenceState(value.observedAt(), value.reliable(), now) != EvidenceState.KNOWN) {
throw AssetDetailDomainException.conflict("关联证据不可靠或已过期");
}
return new RelationCommand(value.relationType(), target, safeRef(value.evidenceRef(), "关联证据引用"),
value.observedAt(), true, sha(value.evidenceSha256(), "关联证据SHA"),
required(value.reason(), "关联原因", 500), value.version());
}
StatusCommand normalize(StatusCommand value) {
if (value == null || value.targetStatus() == null) throw AssetDetailDomainException.validation("状态请求不完整");
version(value.version());
return new StatusCommand(value.targetStatus(), required(value.reason(), "状态原因", 500), value.version());
}
void requireTransition(AssetStatus current, AssetStatus target) {
boolean allowed = (current == AssetStatus.DRAFT && target == AssetStatus.ACTIVE)
|| (current == AssetStatus.ACTIVE && target == AssetStatus.DEPRECATED)
|| (current == AssetStatus.DEPRECATED && target == AssetStatus.ARCHIVED);
if (!allowed) throw AssetDetailDomainException.conflict("资产状态不允许该转换");
}
String requestHash(Object value) { return sha256(write(value)); }
String snapshotSha(List<SectionCommand> value) { return sha256(write(value)); }
private List<SectionCommand> sections(List<SectionCommand> values, LocalDateTime now) {
if (values == null || values.size() != SectionType.values().length) {
throw AssetDetailDomainException.validation("详情快照必须完整包含七类章节");
}
EnumSet<SectionType> types = EnumSet.noneOf(SectionType.class);
List<SectionCommand> normalized = new ArrayList<>();
for (SectionCommand value : values) {
if (value == null || value.sectionType() == null || !types.add(value.sectionType())) {
throw AssetDetailDomainException.conflict("详情章节缺失或重复");
}
String sourceType = safeRef(value.sourceType(), "章节来源类型");
String sourceRef = safeRef(value.sourceRef(), "章节来源引用");
String sha = sha(value.payloadSha256(), "章节payloadSha256");
EvidenceState state = evidenceState(value.observedAt(), value.reliable(), now);
String body = state == EvidenceState.KNOWN ? required(value.value(), "章节值", MAX_SECTION_VALUE) : null;
normalized.add(new SectionCommand(value.sectionType(), sourceType, sourceRef, value.observedAt(),
state == EvidenceState.KNOWN, sha, body));
}
normalized.sort(Comparator.comparing(SectionCommand::sectionType));
return List.copyOf(normalized);
}
private static EvidenceState evidenceState(LocalDateTime observedAt, boolean reliable, LocalDateTime now) {
if (!reliable || observedAt == null || observedAt.isAfter(now.plusMinutes(5))
|| observedAt.isBefore(now.minusHours(24))) return EvidenceState.UNKNOWN;
return EvidenceState.KNOWN;
}
private static void version(Long value) {
if (value == null || value < 0) throw AssetDetailDomainException.validation("version无效");
}
private static String safeRef(String value, String label) {
String normalized = required(value, label, 512);
if (!SAFE_REF.matcher(normalized).matches()) throw AssetDetailDomainException.validation(label + "格式无效");
return normalized;
}
private static String sha(String value, String label) {
String normalized = required(value, label, 64).toLowerCase(Locale.ROOT);
if (!SHA256.matcher(normalized).matches()) throw AssetDetailDomainException.validation(label + "必须为SHA-256");
return normalized;
}
private static String required(String value, String label, int max) {
if (value == null || value.isBlank()) throw AssetDetailDomainException.validation(label + "不能为空");
String normalized = value.trim();
if (normalized.length() > max || DANGEROUS.matcher(normalized).matches()) {
throw AssetDetailDomainException.validation(label + "格式无效");
}
return normalized;
}
private String write(Object value) {
try { return mapper.writeValueAsString(value); }
catch (JacksonException exception) { throw AssetDetailDomainException.validation("请求无法序列化"); }
}
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,115 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.datagov.governance.assetdetail.AssetDetailApi.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
@Service
@RequiredArgsConstructor
class AssetDetailService {
private static final String BASE = "/api/governance/v1/asset-details";
private final AssetDetailJdbcRepository repository;
private final AssetDetailPolicy policy;
private final AssetDetailActorProvider actorProvider;
private final TransactionTemplate transactions;
List<AssetView> list() { return repository.list(actorProvider.current()); }
DetailView detail(long rawId) {
long id = positive(rawId); return repository.detail(id, actorProvider.current());
}
WriteView<DetailView> create(String key, CreateCommand raw) {
var actor = actorProvider.current();
var command = policy.normalize(raw, LocalDateTime.now());
return execute(actor, "POST", BASE, key, command, ticket -> {
long id = repository.create(actor, command);
repository.trajectory(actor, id, "CREATE", null, AssetStatus.DRAFT.name(),
ticket.requestId(), "资产详情和首个七章节快照已创建");
return id;
});
}
WriteView<DetailView> snapshot(long rawId, String key, SnapshotCommand raw) {
long id = positive(rawId); var actor = actorProvider.current();
repository.asset(id, actor);
var command = policy.normalize(raw, LocalDateTime.now());
return execute(actor, "POST", BASE + '/' + id + "/snapshots", key, command, ticket -> {
repository.snapshot(actor, id, command);
repository.trajectory(actor, id, "SNAPSHOT", null, null, ticket.requestId(),
"七章节来源快照已追加,UNKNOWN章节值为空");
return id;
});
}
WriteView<DetailView> owner(long rawId, String key, OwnerCommand raw) {
long id = positive(rawId); var actor = actorProvider.current();
repository.asset(id, actor);
var command = policy.normalize(raw, LocalDateTime.now());
return execute(actor, "POST", BASE + '/' + id + "/owners", key, command, ticket -> {
repository.owner(actor, id, command);
repository.trajectory(actor, id, "OWNER", null, null, ticket.requestId(),
"RCP6主体责任引用已追加");
return id;
});
}
WriteView<DetailView> governance(long rawId, String key, GovernanceCommand raw) {
long id = positive(rawId); var actor = actorProvider.current();
repository.asset(id, actor);
var command = policy.normalize(raw, LocalDateTime.now());
return execute(actor, "POST", BASE + '/' + id + "/governance", key, command, ticket -> {
repository.governance(actor, id, command);
repository.trajectory(actor, id, "GOVERNANCE", null, null, ticket.requestId(),
command.reliable() ? "治理证据状态已追加" : "治理证据不足,UNKNOWN值为空");
return id;
});
}
WriteView<DetailView> relation(long rawId, String key, RelationCommand raw) {
long id = positive(rawId); var actor = actorProvider.current();
AssetView asset = repository.asset(id, actor);
var command = policy.normalize(raw, asset.assetRef(), LocalDateTime.now());
return execute(actor, "POST", BASE + '/' + id + "/relations", key, command, ticket -> {
repository.relation(actor, id, command);
repository.trajectory(actor, id, "RELATION", null, null, ticket.requestId(),
"显式证据关联已追加");
return id;
});
}
WriteView<DetailView> status(long rawId, String key, StatusCommand raw) {
long id = positive(rawId); var actor = actorProvider.current();
AssetView asset = repository.asset(id, actor); var command = policy.normalize(raw);
policy.requireTransition(asset.status(), command.targetStatus());
return execute(actor, "POST", BASE + '/' + id + "/status", key, command, ticket -> {
repository.status(actor, id, asset.status(), command);
repository.trajectory(actor, id, "STATUS", asset.status().name(), command.targetStatus().name(),
ticket.requestId(), command.reason());
return id;
});
}
private WriteView<DetailView> execute(AssetDetailActorProvider.Actor actor, String method,
String path, String rawKey, Object command,
Function<AssetDetailJdbcRepository.RequestTicket, Long> work) {
String key = policy.idempotencyKey(rawKey); String hash = policy.requestHash(command);
var ticket = repository.begin(actor, method, path, key, hash);
if (ticket.responseId() != null) return new WriteView<>(ticket.requestId(), repository.detail(ticket.responseId(), actor));
try {
Long id = transactions.execute(status -> {
long changed = work.apply(ticket);
repository.complete(actor, method, path, key, changed);
return changed;
});
if (id == null) throw new IllegalStateException("资产详情事务未返回结果");
return new WriteView<>(ticket.requestId(), repository.detail(id, actor));
} catch (RuntimeException exception) {
try { repository.fail(actor, method, path, key); }
catch (RuntimeException recording) { exception.addSuppressed(recording); }
throw exception;
}
}
private static long positive(long value) {
if (value <= 0) throw AssetDetailDomainException.validation("资产详情ID无效");
return value;
}
}
@@ -0,0 +1,85 @@
package cn.aixunkeji.datagov.governance.assetdetail;
import cn.aixunkeji.datagov.governance.api.scheduling.GovernanceSchedulingService.*;
import cn.aixunkeji.datagov.governance.scheduling.GovernanceSchedulingDubboService;
import cn.aixunkeji.datagov.governance.scheduling.GovernanceWorkflowOwner;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import static cn.aixunkeji.datagov.governance.assetdetail.AssetDetailApi.*;
/** Refreshes a detail snapshot from its exact source identity; status and ownership are untouched. */
@Component
@RequiredArgsConstructor
public class AssetUpdateWorkflowOwner implements GovernanceWorkflowOwner {
private final AssetDetailService service;
private final AssetDetailJdbcRepository repository;
private final AssetDetailCandidateService candidates;
private final AssetDetailActorProvider actors;
private final AssetDetailPolicy policy;
@Override public String type() { return "ASSET_UPDATE"; }
@Override public Binding resolve(Reference reference) { return resolved(reference).binding(); }
@Override public Result execute(Command command) {
var resolved = resolved(command.reference());
if (!command.ownerVersion().equals(resolved.binding().version())
|| !command.ownerSha256().equals(resolved.binding().sha256())) {
return new Result("FAILED", null, "ASSET_UPDATE_BINDING_CHANGED",
"资产或来源证据已变化,请重新发布流程", LocalDateTime.now());
}
var saved = service.snapshot(command.reference().referenceId(), command.idempotencyKey(), resolved.command());
return success(saved.result().asset().assetDetailId());
}
@Override public Result observe(Command command, Result prior) {
var actor = actors.current();
long id = command.reference().referenceId();
repository.asset(id, actor);
var receipt = repository.completedWorkflowRequest(actor, path(id), command.idempotencyKey());
return receipt != null && receipt == id ? success(id) : prior;
}
private Resolved resolved(Reference reference) {
if (reference.options() != null && !reference.options().isEmpty()) {
throw AssetDetailDomainException.validation("资产更新节点不接受自定义来源或快照内容");
}
var actor = actors.current();
if (actor.actorId() != reference.actorId() || actor.organizationId() != reference.orgId()) {
throw AssetDetailDomainException.forbidden();
}
var asset = repository.asset(reference.referenceId(), actor);
if (asset.status() == AssetStatus.ARCHIVED) throw AssetDetailDomainException.conflict("已归档资产不可更新");
var source = candidates.sourceCandidate(asset.entityId());
if (!Objects.equals(asset.entityId(), source.source().entityId())
|| !Objects.equals(asset.assetRef(), source.source().assetRef())
|| !Objects.equals(asset.assetFqn(), source.source().assetFqn())) {
throw AssetDetailDomainException.conflict("资产身份与当前元数据来源不一致,请先核实身份映射");
}
var snapshot = policy.normalize(new SnapshotCommand(source.sections(), asset.version()), LocalDateTime.now());
for (var required : List.of(SectionType.SCHEMA, SectionType.SOURCE)) {
if (snapshot.sections().stream().noneMatch(section -> section.sectionType() == required
&& section.reliable() && section.value() != null && !section.value().isBlank())) {
throw AssetDetailDomainException.unavailable("资产结构或来源证据不可用,请先刷新元数据采集结果");
}
}
// Lineage observation time is generated per read; freeze the evidence itself rather than that clock value.
var evidence = snapshot.sections().stream().map(section -> new Evidence(section.sectionType(), section.sourceType(),
section.sourceRef(), section.reliable(), section.payloadSha256(), section.value())).toList();
String hash = GovernanceSchedulingDubboService.hash(List.of(asset, source.source(), evidence));
return new Resolved(snapshot, new Binding("AUTHORIZED", Long.toString(asset.version()), hash, null));
}
private static String path(long id) { return "/api/governance/v1/asset-details/" + id + "/snapshots"; }
private static Result success(long id) {
return new Result("SUCCEEDED", "/api/governance/v1/asset-details/" + id, null,
"资产来源快照已刷新,缺少证据的章节仍保留 UNKNOWN", LocalDateTime.now());
}
private record Resolved(SnapshotCommand command, Binding binding) { }
private record Evidence(SectionType type, String sourceType, String sourceRef, boolean reliable, String sha256, String value) { }
}
@@ -0,0 +1,18 @@
package cn.aixunkeji.datagov.governance.assetdetail;
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 P33OwnerContext implements PageAssistContextReader {
private final AssetDetailService service;
@Override public String pageId(){return "P33";}
@Override public Snapshot read(Request r){
qualifiers(r);var v=service.detail(numeric(r)).asset();
return snapshot(r,v.version(),"status",v.status(),"version",v.version(),"createTime",v.createTime(),"updateTime",v.updateTime());
}
}
@@ -0,0 +1,71 @@
package cn.aixunkeji.datagov.governance.assetidentity;
import cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.*;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.*;
import static cn.aixunkeji.datagov.governance.assetidentity.AssetIdentityModel.*;
@Component
class AssetCompositionPolicy {
List<Member> validate(Actor actor, Observation root, CompositionCommand command,
Map<Long, Observation> facts, Graph graph, Instant now) {
validateMembers(actor, root, command, facts, graph, now);
Map<Long, List<Member>> edges = new HashMap<>(graph.edges());
edges.put(root.binding().id(), command.members());
// Iterative topological validation avoids stack overflow on long ancestry chains.
Map<Long, Integer> incoming = new HashMap<>();
edges.forEach((id, members) -> {
incoming.putIfAbsent(id, 0);
for (Member member : members) incoming.merge(member.assetId(), 1, Integer::sum);
});
ArrayDeque<Long> ready = new ArrayDeque<>();
incoming.forEach((id, count) -> { if (count == 0) ready.add(id); });
int visited = 0;
while (!ready.isEmpty()) {
long id = ready.remove(); visited++;
for (Member member : edges.getOrDefault(id, List.of())) {
if (incoming.merge(member.assetId(), -1, Integer::sum) == 0) ready.add(member.assetId());
}
}
if (visited != incoming.size()) throw failure(ErrorCode.SOURCE_CONFLICT);
return command.members().stream().sorted(Comparator.comparingLong(Member::assetId)).toList();
}
void validateMembers(Actor actor, Observation root, CompositionCommand command,
Map<Long, Observation> facts, Graph graph, Instant now) {
if (graph == null || !graph.complete()) throw failure(ErrorCode.OWNER_UNKNOWN);
if (graph.edges().size() > 10000) throw failure(ErrorCode.UNSUPPORTED);
var identities = new AssetIdentityPolicy();
identities.verify(actor, root.binding(), root, now);
requireFrozen(root, command.assetBusinessVersion());
Set<Long> unique = new HashSet<>();
for (Member member : command.members()) {
if (member.assetId() == root.binding().id() || !unique.add(member.assetId())) throw failure(ErrorCode.SOURCE_CONFLICT);
}
for (Member member : reachable(root.binding().id(), command, graph)) {
Observation fact = facts.get(member.assetId());
if (fact == null) throw failure(ErrorCode.OWNER_UNKNOWN);
identities.verify(actor, fact.binding(), fact, now);
requireFrozen(fact, member.businessVersion());
}
}
static List<Member> reachable(long rootId, CompositionCommand command, Graph graph) {
if (graph == null || !graph.complete()) throw failure(ErrorCode.OWNER_UNKNOWN);
Map<Long, List<Member>> edges = new HashMap<>(graph.edges()); edges.put(rootId, command.members());
List<Member> result = new ArrayList<>();
Set<Long> visited = new HashSet<>(); ArrayDeque<Long> queue = new ArrayDeque<>(); queue.add(rootId);
while (!queue.isEmpty()) {
long id = queue.remove(); if (!visited.add(id)) continue;
for (Member member : edges.getOrDefault(id, List.of())) {
result.add(member); queue.add(member.assetId());
}
if (result.size() > 11000) throw failure(ErrorCode.UNSUPPORTED);
}
return List.copyOf(result);
}
private static void requireFrozen(Observation observed, long expectedVersion) {
if (observed.binding().kind() != Kind.LIFECYCLE || observed.binding().state() != AssetState.ACTIVE
|| observed.binding().businessVersion() <= 0 || observed.binding().businessVersion() != expectedVersion)
throw failure(ErrorCode.VERSION_CONFLICT);
}
}
@@ -0,0 +1,59 @@
package cn.aixunkeji.datagov.governance.assetidentity;
import cn.aixunkeji.common.satoken.utils.LoginHelper;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.stereotype.Component;
import java.util.Set;
import java.time.Instant;
import cn.aixunkeji.system.api.RemoteUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import static cn.aixunkeji.datagov.governance.assetidentity.AssetIdentityModel.*;
import static cn.aixunkeji.datagov.governance.api.assetupgrade.AssetUpgradeOwner.ErrorCode.*;
@Component
class AssetIdentityActorProvider {
@DubboReference(check = false, retries = 0)
private RemoteUserService users;
Actor views() {
Actor actor = current();
project(actor, "IDENTITY_DETAIL_VIEW", false);
project(actor, "IDENTITY_LIFECYCLE_VIEW", false);
return new Actor(actor.actorId(), actor.scope(), Set.of(AssetIdentityService.DETAIL_VIEW, AssetIdentityService.LIFECYCLE_VIEW));
}
Actor draft() { Actor actor = views(); project(actor, "IDENTITY_BINDING_DRAFT", false); return actor; }
BindingCapabilities capabilities(Actor actor) {
return new BindingCapabilities(allowed(actor, "IDENTITY_BINDING_DRAFT"),
allowed(actor, "IDENTITY_RECONCILE"), allowed(actor, "IDENTITY_REVOKE"));
}
private boolean allowed(Actor actor, String purpose) {
try { project(actor, purpose, false); return true; }
catch (Failure unavailableOrDenied) { return false; }
}
Actor maintenance(boolean revoke) {
Actor actor = views(); project(actor, revoke ? "IDENTITY_REVOKE" : "IDENTITY_RECONCILE", true); return actor;
}
private void project(Actor actor, String purpose, boolean dedicated) {
Instant started = Instant.now();
try {
var decision = users.resolveAssetActor(actor.actorId(), actor.scope().departmentId(), purpose);
Instant now = Instant.now();
if (decision == null || !decision.allowed() || decision.userId() != actor.actorId()
|| decision.deptId() != actor.scope().departmentId() || !purpose.equals(decision.purpose())
|| decision.checkedAt() == null || decision.checkedAt().isBefore(started.minusSeconds(5))
|| decision.checkedAt().isAfter(now.plusSeconds(5)) || decision.checkedAt().isBefore(now.minusSeconds(30)))
throw dedicated ? authPending() : failure(FORBIDDEN);
} catch (Failure failure) { throw failure; }
catch (RuntimeException | LinkageError unavailable) { throw dedicated ? authPending() : failure(OWNER_UNKNOWN); }
}
Actor current() {
if (!StpUtil.isLogin()) throw failure(UNAUTHENTICATED);
Long actor = LoginHelper.getUserId();
Long department = LoginHelper.getDeptId();
if (actor == null || actor <= 0 || department == null || department <= 0) throw failure(UNAUTHENTICATED);
// Controller-approved V1 compatibility with the existing local Owners.
// Both columns are legacy scope keys, not independent enterprise/tenant identities.
Scope scope = new Scope(department, department);
return new Actor(actor, scope, Set.copyOf(StpUtil.getPermissionList()));
}
}

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