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:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,7 @@ import org.springframework.web.server.ResponseStatusException;
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import com.dsasp.server.common.util.UserSession;
|
||||
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.TypedPageSchemaValidator;
|
||||
|
||||
@@ -75,6 +76,7 @@ public class PageSchemaController {
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final PageComponentRegistry componentRegistry;
|
||||
private final TypedPageSchemaValidator typedSchemaValidator;
|
||||
private final PageSchemaWriter pageSchemaWriter;
|
||||
|
||||
@Autowired
|
||||
public PageSchemaController(JdbcTemplate jdbcTemplate) {
|
||||
@@ -85,6 +87,7 @@ public class PageSchemaController {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.componentRegistry = componentRegistry;
|
||||
this.typedSchemaValidator = new TypedPageSchemaValidator(SCHEMA_MAPPER, componentRegistry);
|
||||
this.pageSchemaWriter = new PageSchemaWriter(jdbcTemplate);
|
||||
}
|
||||
|
||||
@Operation(summary = "查询 typed page schema 组件能力表",
|
||||
@@ -237,6 +240,35 @@ public class PageSchemaController {
|
||||
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(还原标准版)
|
||||
|
||||
@Operation(summary = "还原标准版(删除 overlay,仅管理员)",
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -441,6 +441,61 @@ class PageSchemaControllerTest {
|
||||
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 工具 ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void setAdminSession() {
|
||||
|
||||
Reference in New Issue
Block a user