feat(page-schema): converge net-new standard writes to single PageSchemaWriter (M3a)

sys_page_schema standard layer had two runtime writers: the converter import CLI and AiLocalReleaseExecutor's raw JDBC INSERT (the critic-flagged net-new bypass). Introduce PageSchemaWriter as the single runtime write function (typed-recipe validation warn-not-block + etag + UPSERT), and route both a new admin-gated PUT /api/page/schema/{id}/standard endpoint (net-new producer for the design-center 'new feature' path) and AiLocalReleaseExecutor.applyPageSchema through it. No remaining raw INSERT into sys_page_schema in the AI runtime write path.

Scope: page_schema runtime write only. The deployment-package SQL-text generator (AiAgentService.pageSchemaSql, offline human-apply artifact) and SchemaImportCli (batch converter import) are separate legitimate paths. AiLocalReleaseExecutor sys_serviceflow/sys_menu raw writes remain (follow-on). Completion = code-complete, integration-pending (end-to-end render proof env-gated).

Tests: PageSchemaWriterTest (4) + PageSchemaControllerTest putStandard success/403/split (27 total) + AiLocalReleaseExecutorTest/AiAgentApiPipelineTest unchanged-green. TDD.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-06-19 17:21:06 +08:00
parent da3ad35821
commit d3b88467e0
5 changed files with 264 additions and 26 deletions

View File

@@ -1,13 +1,9 @@
package com.eip4.platform.ai.service; package com.eip4.platform.ai.service;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HexFormat;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@@ -22,6 +18,7 @@ import org.springframework.web.server.ResponseStatusException;
import com.eip4.platform.ai.model.AiApplyStepResult; import com.eip4.platform.ai.model.AiApplyStepResult;
import com.eip4.platform.ai.model.AiArtifactType; import com.eip4.platform.ai.model.AiArtifactType;
import com.eip4.platform.ai.model.AiDraft; import com.eip4.platform.ai.model.AiDraft;
import com.eip4.platform.metadata.schema.PageSchemaWriter;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@@ -31,11 +28,14 @@ public class AiLocalReleaseExecutor {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final AiSmokeHttpClient httpClient; private final AiSmokeHttpClient httpClient;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final PageSchemaWriter pageSchemaWriter;
public AiLocalReleaseExecutor(JdbcTemplate jdbcTemplate, AiSmokeHttpClient httpClient, ObjectMapper objectMapper) { public AiLocalReleaseExecutor(JdbcTemplate jdbcTemplate, AiSmokeHttpClient httpClient, ObjectMapper objectMapper) {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
this.httpClient = httpClient; this.httpClient = httpClient;
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
// M3a 收口:标准层页面 schema 写统一走 PageSchemaWriter(与设计中心新建端点共用单一写真相)
this.pageSchemaWriter = new PageSchemaWriter(jdbcTemplate);
} }
public List<AiApplyStepResult> apply(String baseUrl, List<AiDraft> drafts) { public List<AiApplyStepResult> apply(String baseUrl, List<AiDraft> drafts) {
@@ -152,20 +152,10 @@ public class AiLocalReleaseExecutor {
} }
private AiApplyStepResult applyPageSchema(AiDraft draft, int index) throws Exception { private AiApplyStepResult applyPageSchema(AiDraft draft, int index) throws Exception {
// M3a 收口:不再裸 INSERT sys_page_schema;走 PageSchemaWriter 唯一写真相(typed 校验告警 + etag + UPSERT)
String schemaJson = objectMapper.writeValueAsString(draft.payload()); String schemaJson = objectMapper.writeValueAsString(draft.payload());
String etag = sha256(schemaJson); String name = draft.payload().path("title").asText(draft.targetId());
long now = System.currentTimeMillis(); String etag = pageSchemaWriter.upsertStandard(draft.targetId(), name, schemaJson, "AI_AGENT");
jdbcTemplate.update("""
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
VALUES (?, ?, ?::jsonb, ?, 1, ?)
ON CONFLICT (template_id) DO UPDATE SET
name = EXCLUDED.name,
schema_json = EXCLUDED.schema_json,
schema_etag = EXCLUDED.schema_etag,
version = sys_page_schema.version + 1,
update_time = EXCLUDED.update_time
""",
draft.targetId(), draft.payload().path("title").asText(draft.targetId()), schemaJson, etag, now);
return applied(index, draft, "页面 schema 已发布", Map.of("templateId", draft.targetId(), "etag", etag)); return applied(index, draft, "页面 schema 已发布", Map.of("templateId", draft.targetId(), "etag", etag));
} }
@@ -321,15 +311,6 @@ public class AiLocalReleaseExecutor {
return value == null ? "" : value.trim(); return value == null ? "" : value.trim();
} }
private static String sha256(String text) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex);
}
}
private static class ApplyContext { private static class ApplyContext {
private final URI base; private final URI base;
private String entityId = ""; private String entityId = "";

View File

@@ -0,0 +1,88 @@
package com.eip4.platform.metadata.schema;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
/**
* 标准层 {@code sys_page_schema} 的<b>唯一</b>写入口(净新页 / AI 产物 / 设计中心新建都走这里)。
*
* <p>背景(M3a 收口):标准层原先有两个写法——转换器批量导入(SchemaImportCli)与 AI 运行时
* {@code AiLocalReleaseExecutor} 的裸 JDBC INSERT。后者绕过校验/审计/etag 口径,形成第二写路径。
* 本类把净新写收敛为单一函数:{@link com.eip4.platform.metadata.web.PageSchemaController} 的标准层写端点
* 与 {@code AiLocalReleaseExecutor.applyPageSchema} 都调用它,消除旁路裸 INSERT。
*
* <p>校验口径与 {@code putOverlay} 分流一致:typed-recipe 校验只观测告警、<b>不阻断</b>(设计器/AI
* 产物可能用全量 amis 组件,严格 typed 闸保留在 {@code /api/page/schema/validate} + AI 草稿 pipeline)。
*/
@Component
public class PageSchemaWriter {
private static final Logger log = LoggerFactory.getLogger(PageSchemaWriter.class);
private final JdbcTemplate jdbcTemplate;
private final TypedPageSchemaValidator typedValidator;
public PageSchemaWriter(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.typedValidator = TypedPageSchemaValidator.defaults();
}
/**
* UPSERT 标准层页面 schema。存在则 version+1,否则 version=1。
*
* @param templateId 页面模板 id(主键)
* @param name 页面名(缺省回退 templateId)
* @param schemaJson 完整 amis schema JSON 字符串
* @param operator 写入者标识(审计;如 AI_AGENT / 管理员 userId)
* @return 写入内容的 sha256 etag
*/
public String upsertStandard(String templateId, String name, String schemaJson, String operator) {
if (templateId == null || templateId.isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "templateId 不能为空");
}
if (schemaJson == null || schemaJson.isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "schemaJson 不能为空");
}
// 分流:typed-recipe 校验只告警不阻断(与 putOverlay 一致)
TypedPageSchemaReport validation = typedValidator.validate(schemaJson);
if (!validation.valid()) {
log.warn("[standard-write] typed-recipe 校验 {} 项告警(不阻断)templateId={}: {}",
validation.issues().size(), templateId, validation.issues());
}
String etag = sha256(schemaJson);
String safeName = name == null || name.isBlank() ? templateId : name;
long now = System.currentTimeMillis();
jdbcTemplate.update("""
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
VALUES (?, ?, ?::jsonb, ?, 1, ?)
ON CONFLICT (template_id) DO UPDATE SET
name = EXCLUDED.name,
schema_json = EXCLUDED.schema_json,
schema_etag = EXCLUDED.schema_etag,
version = sys_page_schema.version + 1,
update_time = EXCLUDED.update_time
""",
templateId, safeName, schemaJson, etag, now);
log.info("[standard-write] operator={} templateId={} etag={}",
operator == null || operator.isBlank() ? "UNKNOWN" : operator, templateId, etag);
return etag;
}
static String sha256(String text) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException ex) {
throw new IllegalStateException(ex);
}
}
}

View File

@@ -31,6 +31,7 @@ import org.springframework.web.server.ResponseStatusException;
import com.dsasp.server.common.user.service.LoggedInUser; import com.dsasp.server.common.user.service.LoggedInUser;
import com.dsasp.server.common.util.UserSession; import com.dsasp.server.common.util.UserSession;
import com.eip4.platform.metadata.schema.PageComponentRegistry; import com.eip4.platform.metadata.schema.PageComponentRegistry;
import com.eip4.platform.metadata.schema.PageSchemaWriter;
import com.eip4.platform.metadata.schema.TypedPageSchemaReport; import com.eip4.platform.metadata.schema.TypedPageSchemaReport;
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator; import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
@@ -75,6 +76,7 @@ public class PageSchemaController {
private final JdbcTemplate jdbcTemplate; private final JdbcTemplate jdbcTemplate;
private final PageComponentRegistry componentRegistry; private final PageComponentRegistry componentRegistry;
private final TypedPageSchemaValidator typedSchemaValidator; private final TypedPageSchemaValidator typedSchemaValidator;
private final PageSchemaWriter pageSchemaWriter;
@Autowired @Autowired
public PageSchemaController(JdbcTemplate jdbcTemplate) { public PageSchemaController(JdbcTemplate jdbcTemplate) {
@@ -85,6 +87,7 @@ public class PageSchemaController {
this.jdbcTemplate = jdbcTemplate; this.jdbcTemplate = jdbcTemplate;
this.componentRegistry = componentRegistry; this.componentRegistry = componentRegistry;
this.typedSchemaValidator = new TypedPageSchemaValidator(SCHEMA_MAPPER, componentRegistry); this.typedSchemaValidator = new TypedPageSchemaValidator(SCHEMA_MAPPER, componentRegistry);
this.pageSchemaWriter = new PageSchemaWriter(jdbcTemplate);
} }
@Operation(summary = "查询 typed page schema 组件能力表", @Operation(summary = "查询 typed page schema 组件能力表",
@@ -237,6 +240,35 @@ public class PageSchemaController {
return ResponseEntity.ok(ok("overlay 保存成功", data)); return ResponseEntity.ok(ok("overlay 保存成功", data));
} }
// ================================================================ PUT standard(写标准层·净新页/设计中心新建/AI 产物)
@Operation(summary = "写入/更新标准层页面 schema(净新页/设计中心新建/AI 产物,仅管理员)",
description = "标准层 sys_page_schema 的唯一写入口(与 AI 运行时共用 PageSchemaWriter,消除旁路裸 INSERT);"
+ "typed-recipe 校验只告警不阻断;?name= 可选,缺省取 templateId")
@PutMapping("/api/page/schema/{templateId}/standard")
public ResponseEntity<Map<String, Object>> putStandard(
@PathVariable String templateId,
@RequestParam(value = "name", required = false) String name,
@RequestBody String schemaJsonRaw) {
requireAdmin();
if (schemaJsonRaw == null || schemaJsonRaw.isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体不能为空");
}
try {
String etag = pageSchemaWriter.upsertStandard(templateId, name, schemaJsonRaw, currentUserId());
Map<String, Object> data = new LinkedHashMap<>();
data.put("templateId", templateId);
data.put("etag", etag);
return ResponseEntity.ok(ok("标准层 schema 已写入", data));
} catch (DataAccessException ex) {
log.error("[standard-write] 保存失败 templateId={}: {}", templateId, ex.getMessage());
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(fail("标准层写入失败:" + ex.getMessage()));
}
}
// ================================================================ DELETE overlay(还原标准版) // ================================================================ DELETE overlay(还原标准版)
@Operation(summary = "还原标准版(删除 overlay,仅管理员)", @Operation(summary = "还原标准版(删除 overlay,仅管理员)",

View File

@@ -0,0 +1,82 @@
package com.eip4.platform.metadata.schema;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.server.ResponseStatusException;
/** {@link PageSchemaWriter} 单测(mock JdbcTemplate,不连库)。 */
class PageSchemaWriterTest {
private static final String TID = "eip4ai-customer-level";
@Test
@DisplayName("1. upsertStandard 返回 sha256 etag 并 UPSERT 标准层一次")
void upsertWritesOnceAndReturnsEtag() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.update(anyString(), any(), any(), any(), any(), any())).thenReturn(1);
PageSchemaWriter writer = new PageSchemaWriter(jdbc);
String schema = "{\"type\":\"page\",\"title\":\"客户等级\",\"body\":{\"type\":\"crud\"}}";
String etag = writer.upsertStandard(TID, "客户等级", schema, "AI_AGENT");
assertEquals(PageSchemaWriter.sha256(schema), etag);
assertEquals(64, etag.length());
// 标准层只被这一个函数写一次
verify(jdbc).update(anyString(), eq(TID), eq("客户等级"), eq(schema), eq(etag), any());
}
@Test
@DisplayName("2. 分流:含未注册组件(search-box)的页也写入,typed 校验只告警不阻断")
void unregisteredComponentsAreWarnedNotBlocked() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.update(anyString(), any(), any(), any(), any(), any())).thenReturn(1);
PageSchemaWriter writer = new PageSchemaWriter(jdbc);
String legacyish = "{\"type\":\"page\",\"body\":{\"type\":\"crud\","
+ "\"filter\":{\"type\":\"form\",\"body\":[{\"type\":\"search-box\"}]}}}";
// 不抛、正常返回 etag
String etag = writer.upsertStandard(TID, null, legacyish, "AI_AGENT");
assertEquals(64, etag.length());
verify(jdbc).update(anyString(), eq(TID), eq(TID), eq(legacyish), eq(etag), any());
}
@Test
@DisplayName("3. name 缺省回退 templateId")
void nameFallsBackToTemplateId() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.update(anyString(), any(), any(), any(), any(), any())).thenReturn(1);
PageSchemaWriter writer = new PageSchemaWriter(jdbc);
writer.upsertStandard(TID, " ", "{\"type\":\"page\"}", "AI_AGENT");
verify(jdbc).update(anyString(), eq(TID), eq(TID), anyString(), anyString(), any());
}
@Test
@DisplayName("4. templateId/schemaJson 为空 → 400,不写库")
void blankArgsRejected() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
PageSchemaWriter writer = new PageSchemaWriter(jdbc);
ResponseStatusException e1 = assertThrows(ResponseStatusException.class,
() -> writer.upsertStandard(" ", "n", "{\"type\":\"page\"}", "AI_AGENT"));
assertEquals(HttpStatus.BAD_REQUEST, e1.getStatusCode());
ResponseStatusException e2 = assertThrows(ResponseStatusException.class,
() -> writer.upsertStandard(TID, "n", " ", "AI_AGENT"));
assertEquals(HttpStatus.BAD_REQUEST, e2.getStatusCode());
assertTrue(e2.getReason() != null);
}
}

View File

@@ -441,6 +441,61 @@ class PageSchemaControllerTest {
clearSession(); clearSession();
} }
// ── M3a 标准层写端点(净新页/设计中心新建/AI 产物,单一写真相) ──────────────
@Test
@DisplayName("21. PUT standard 写标准层成功(管理员),UPSERT 一次")
void putStandardSuccessAsAdmin() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.update(anyString(), any(), any(), any(), any(), any())).thenReturn(1);
PageSchemaController c = new PageSchemaController(jdbc);
setAdminSession();
var resp = c.putStandard(TID, "客户等级", "{\"type\":\"page\",\"title\":\"客户等级\"}");
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
@SuppressWarnings("unchecked")
Map<String, Object> data = (Map<String, Object>) resp.getBody().get("data");
assertEquals(TID, data.get("templateId"));
assertTrue(data.get("etag") != null);
verify(jdbc).update(anyString(), any(), any(), any(), any(), any());
clearSession();
}
@Test
@DisplayName("22. PUT standard 非管理员 → 403")
void putStandardForbiddenForNonAdmin() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.queryForObject(anyString(), eq(Integer.class), anyString())).thenReturn(0);
PageSchemaController c = new PageSchemaController(jdbc);
setNonAdminSession("non-admin-uid");
org.springframework.web.server.ResponseStatusException ex =
org.junit.jupiter.api.Assertions.assertThrows(
org.springframework.web.server.ResponseStatusException.class,
() -> c.putStandard(TID, "n", "{\"type\":\"page\"}"));
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
clearSession();
}
@Test
@DisplayName("23. PUT standard 分流:含 search-box 的净新页也写入(typed 校验不阻断)")
void putStandardAllowsLegacyComponents() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
when(jdbc.update(anyString(), any(), any(), any(), any(), any())).thenReturn(1);
PageSchemaController c = new PageSchemaController(jdbc);
setAdminSession();
String page = "{\"type\":\"page\",\"body\":{\"type\":\"crud\","
+ "\"filter\":{\"type\":\"form\",\"body\":[{\"type\":\"search-box\"}]}}}";
var resp = c.putStandard(TID, null, page);
assertEquals(HttpStatus.OK, resp.getStatusCode());
verify(jdbc).update(anyString(), any(), any(), any(), any(), any());
clearSession();
}
// ── Session 工具 ───────────────────────────────────────────────────────── // ── Session 工具 ─────────────────────────────────────────────────────────
private static void setAdminSession() { private static void setAdminSession() {