feat: add typed page schema registry

This commit is contained in:
2026-06-17 08:39:51 +08:00
parent b05f0e89b5
commit 5eb95a4ef4
12 changed files with 408 additions and 2 deletions

View File

@@ -0,0 +1,10 @@
package com.eip4.platform.metadata.schema;
import java.util.List;
public record PageComponentDefinition(
String type,
String category,
List<String> capabilities,
List<String> allowedActions) {
}

View File

@@ -0,0 +1,87 @@
package com.eip4.platform.metadata.schema;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public final class PageComponentRegistry {
public static final int VERSION = 1;
private final Map<String, PageComponentDefinition> components;
private PageComponentRegistry(Map<String, PageComponentDefinition> components) {
this.components = Collections.unmodifiableMap(new LinkedHashMap<>(components));
}
public static PageComponentRegistry defaults() {
Map<String, PageComponentDefinition> map = new LinkedHashMap<>();
register(map, "page", "layout", List.of("page-root"), List.of());
register(map, "crud", "data", List.of("list", "pagination", "toolbar", "columns"), List.of());
register(map, "form", "data", List.of("submit", "validation", "api"), List.of("submit", "reset"));
register(map, "operation", "data", List.of("row-actions"), List.of());
register(map, "service", "data", List.of("remote-schema", "remote-data"), List.of());
register(map, "button", "action", List.of("dialog", "ajax", "drawer", "link", "reload"), List.of(
"ajax", "dialog", "drawer", "link", "url", "reload", "submit", "reset", "cancel", "copy",
"download", "toast", "confirm"));
register(map, "tpl", "display", List.of("template-text"), List.of());
register(map, "static", "display", List.of("readonly"), List.of());
register(map, "static-text", "display", List.of("readonly"), List.of());
register(map, "wrapper", "layout", List.of("container"), List.of());
register(map, "container", "layout", List.of("container"), List.of());
register(map, "grid", "layout", List.of("columns"), List.of());
register(map, "hbox", "layout", List.of("columns"), List.of());
register(map, "group", "layout", List.of("form-group"), List.of());
register(map, "input-text", "field", List.of("text", "required"), List.of());
register(map, "textarea", "field", List.of("text", "multiline", "required"), List.of());
register(map, "input-password", "field", List.of("password", "required"), List.of());
register(map, "input-number", "field", List.of("number", "required"), List.of());
register(map, "input-date", "field", List.of("date", "required"), List.of());
register(map, "input-datetime", "field", List.of("datetime", "required"), List.of());
register(map, "input-time", "field", List.of("time", "required"), List.of());
register(map, "input-month", "field", List.of("month", "required"), List.of());
register(map, "input-quarter", "field", List.of("quarter", "required"), List.of());
register(map, "input-year", "field", List.of("year", "required"), List.of());
register(map, "switch", "field", List.of("boolean"), List.of());
register(map, "checkbox", "field", List.of("boolean"), List.of());
register(map, "checkboxes", "field", List.of("multi-option"), List.of());
register(map, "radios", "field", List.of("single-option"), List.of());
register(map, "select", "field", List.of("single-option", "remote-options"), List.of());
register(map, "picker", "field", List.of("dialog-picker", "remote-options"), List.of());
register(map, "input-tree", "field", List.of("tree-options"), List.of());
register(map, "input-tag", "field", List.of("tags"), List.of());
register(map, "input-color", "field", List.of("color"), List.of());
register(map, "input-file", "field", List.of("upload"), List.of());
register(map, "input-image", "field", List.of("image-upload"), List.of());
register(map, "input-table", "field", List.of("editable-table"), List.of());
register(map, "hidden", "field", List.of("hidden-value"), List.of());
return new PageComponentRegistry(map);
}
public boolean supportsComponent(String type) {
return components.containsKey(type);
}
public boolean supportsAction(String componentType, String actionType) {
PageComponentDefinition definition = components.get(componentType);
return definition != null && definition.allowedActions().contains(actionType);
}
public Map<String, PageComponentDefinition> components() {
return components;
}
public Map<String, Object> toResponse() {
Map<String, Object> data = new LinkedHashMap<>();
data.put("schemaVersion", VERSION);
data.put("components", components.values());
return data;
}
private static void register(Map<String, PageComponentDefinition> map, String type, String category,
List<String> capabilities, List<String> allowedActions) {
map.put(type, new PageComponentDefinition(type, category, List.copyOf(capabilities),
List.copyOf(allowedActions)));
}
}

View File

@@ -0,0 +1,4 @@
package com.eip4.platform.metadata.schema;
public record TypedPageSchemaIssue(String path, String code, String message) {
}

View File

@@ -0,0 +1,12 @@
package com.eip4.platform.metadata.schema;
import java.util.List;
import java.util.Set;
public record TypedPageSchemaReport(
int schemaVersion,
boolean valid,
List<TypedPageSchemaIssue> issues,
Set<String> usedComponents,
Set<String> usedActions) {
}

View File

@@ -0,0 +1,100 @@
package com.eip4.platform.metadata.schema;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public final class TypedPageSchemaValidator {
private final ObjectMapper objectMapper;
private final PageComponentRegistry registry;
public TypedPageSchemaValidator(ObjectMapper objectMapper, PageComponentRegistry registry) {
this.objectMapper = objectMapper;
this.registry = registry;
}
public static TypedPageSchemaValidator defaults() {
return new TypedPageSchemaValidator(new ObjectMapper(), PageComponentRegistry.defaults());
}
public TypedPageSchemaReport validate(String schemaJson) {
List<TypedPageSchemaIssue> issues = new ArrayList<>();
Set<String> usedComponents = new LinkedHashSet<>();
Set<String> usedActions = new LinkedHashSet<>();
JsonNode root;
try {
root = objectMapper.readTree(schemaJson);
} catch (JacksonException ex) {
issues.add(new TypedPageSchemaIssue("$", "INVALID_JSON", "schema 不是合法 JSON: " + ex.getOriginalMessage()));
return report(issues, usedComponents, usedActions);
}
if (root == null || !root.isObject()) {
issues.add(new TypedPageSchemaIssue("$", "ROOT_NOT_OBJECT", "页面 schema 根节点必须是 JSON object"));
return report(issues, usedComponents, usedActions);
}
if (!"page".equals(root.path("type").asText(""))) {
issues.add(new TypedPageSchemaIssue("$.type", "ROOT_TYPE_NOT_PAGE", "页面 schema 根节点 type 必须是 page"));
}
visit(root, "$", issues, usedComponents, usedActions);
return report(issues, usedComponents, usedActions);
}
private void visit(JsonNode node, String path, List<TypedPageSchemaIssue> issues,
Set<String> usedComponents, Set<String> usedActions) {
if (node.isObject()) {
validateObject(node, path, issues, usedComponents, usedActions);
node.properties().forEach(entry -> visit(entry.getValue(), childPath(path, entry.getKey()),
issues, usedComponents, usedActions));
return;
}
if (node.isArray()) {
for (int i = 0; i < node.size(); i++) {
visit(node.get(i), path + "[" + i + "]", issues, usedComponents, usedActions);
}
}
}
private void validateObject(JsonNode node, String path, List<TypedPageSchemaIssue> issues,
Set<String> usedComponents, Set<String> usedActions) {
String componentType = node.path("type").asText("");
if (!componentType.isBlank()) {
usedComponents.add(componentType);
if (!registry.supportsComponent(componentType)) {
issues.add(new TypedPageSchemaIssue(path + ".type", "UNSUPPORTED_COMPONENT",
"组件未注册: " + componentType));
}
}
String actionType = node.path("actionType").asText("");
if (!actionType.isBlank()) {
usedActions.add(actionType);
if (componentType.isBlank()) {
issues.add(new TypedPageSchemaIssue(path + ".actionType", "ACTION_WITHOUT_COMPONENT",
"actionType 必须绑定到有 type 的组件"));
} else if (!registry.supportsAction(componentType, actionType)) {
issues.add(new TypedPageSchemaIssue(path + ".actionType", "UNSUPPORTED_ACTION",
"组件 " + componentType + " 不支持 actionType: " + actionType));
}
}
}
private TypedPageSchemaReport report(List<TypedPageSchemaIssue> issues, Set<String> usedComponents,
Set<String> usedActions) {
return new TypedPageSchemaReport(PageComponentRegistry.VERSION, issues.isEmpty(), List.copyOf(issues),
Collections.unmodifiableSet(new LinkedHashSet<>(usedComponents)),
Collections.unmodifiableSet(new LinkedHashSet<>(usedActions)));
}
private String childPath(String path, String field) {
if (field.matches("[A-Za-z_][A-Za-z0-9_]*")) {
return path + "." + field;
}
return path + "['" + field.replace("'", "\\'") + "']";
}
}

View File

@@ -19,6 +19,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@@ -28,6 +29,9 @@ 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.TypedPageSchemaReport;
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -66,9 +70,35 @@ public class PageSchemaController {
public static final String HEADER_SCHEMA_LAYER = "X-Schema-Layer";
private final JdbcTemplate jdbcTemplate;
private final PageComponentRegistry componentRegistry;
private final TypedPageSchemaValidator typedSchemaValidator;
public PageSchemaController(JdbcTemplate jdbcTemplate) {
this(jdbcTemplate, PageComponentRegistry.defaults());
}
PageSchemaController(JdbcTemplate jdbcTemplate, PageComponentRegistry componentRegistry) {
this.jdbcTemplate = jdbcTemplate;
this.componentRegistry = componentRegistry;
this.typedSchemaValidator = new TypedPageSchemaValidator(SCHEMA_MAPPER, componentRegistry);
}
@Operation(summary = "查询 typed page schema 组件能力表",
description = "AI Agent 和设计器共用;未注册组件不能保存为 overlay。")
@GetMapping("/api/page/schema/components")
public ResponseEntity<Map<String, Object>> components() {
return ResponseEntity.ok(ok("component registry", componentRegistry.toResponse()));
}
@Operation(summary = "校验 typed page schema",
description = "校验根类型、组件注册和 actionType 能力;不写库。")
@PostMapping("/api/page/schema/validate")
public ResponseEntity<Map<String, Object>> validateSchema(@RequestBody String schemaJsonRaw) {
TypedPageSchemaReport report = typedSchemaValidator.validate(schemaJsonRaw == null ? "" : schemaJsonRaw);
if (!report.valid()) {
return ResponseEntity.badRequest().body(fail("typed schema 校验失败", validationData(report)));
}
return ResponseEntity.ok(ok("typed schema 校验通过", validationData(report)));
}
// ================================================================ GET 读取
@@ -139,6 +169,10 @@ public class PageSchemaController {
if (schemaJsonRaw == null || schemaJsonRaw.isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体不能为空");
}
TypedPageSchemaReport validation = typedSchemaValidator.validate(schemaJsonRaw);
if (!validation.valid()) {
return ResponseEntity.badRequest().body(fail("typed schema 校验失败", validationData(validation)));
}
// 计算 overlay etag
String overlayEtag = sha256(schemaJsonRaw);
@@ -335,9 +369,24 @@ public class PageSchemaController {
}
private static Map<String, Object> fail(String msg) {
return fail(msg, null);
}
private static Map<String, Object> fail(String msg, Map<String, Object> data) {
Map<String, Object> r = new LinkedHashMap<>();
r.put("status", 1);
r.put("msg", msg);
if (data != null) r.put("data", data);
return r;
}
private static Map<String, Object> validationData(TypedPageSchemaReport report) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("schemaVersion", report.schemaVersion());
data.put("valid", report.valid());
data.put("issues", report.issues());
data.put("usedComponents", report.usedComponents());
data.put("usedActions", report.usedActions());
return data;
}
}

View File

@@ -0,0 +1,67 @@
package com.eip4.platform.metadata.schema;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class TypedPageSchemaValidatorTest {
private final TypedPageSchemaValidator validator = TypedPageSchemaValidator.defaults();
@Test
void acceptsRegisteredCrudFormAndButtonActions() {
TypedPageSchemaReport report = validator.validate("""
{
"type": "page",
"body": [{
"type": "crud",
"columns": [{
"type": "operation",
"buttons": [
{"type": "button", "actionType": "dialog", "dialog": {"body": {"type": "form"}}},
{"type": "button", "actionType": "ajax"}
]
}]
}]
}
""");
assertTrue(report.valid());
assertTrue(report.usedComponents().contains("crud"));
assertTrue(report.usedActions().contains("dialog"));
assertTrue(report.usedActions().contains("ajax"));
}
@Test
void rejectsUnsupportedComponent() {
TypedPageSchemaReport report = validator.validate("""
{"type":"page","body":{"type":"unknown-widget"}}
""");
assertFalse(report.valid());
assertEquals("UNSUPPORTED_COMPONENT", report.issues().get(0).code());
assertTrue(report.issues().get(0).path().contains("$.body.type"));
}
@Test
void rejectsUnsupportedActionForComponent() {
TypedPageSchemaReport report = validator.validate("""
{"type":"page","body":{"type":"form","actionType":"dialog"}}
""");
assertFalse(report.valid());
assertEquals("UNSUPPORTED_ACTION", report.issues().get(0).code());
}
@Test
void requiresPageRoot() {
TypedPageSchemaReport report = validator.validate("""
{"type":"crud"}
""");
assertFalse(report.valid());
assertEquals("ROOT_TYPE_NOT_PAGE", report.issues().get(0).code());
}
}

View File

@@ -353,6 +353,46 @@ class PageSchemaControllerTest {
assertTrue(hash.matches("[0-9a-f]{64}"));
}
@Test
@DisplayName("18. 组件能力表端点返回 schemaVersion 和已注册组件")
void componentRegistryEndpoint() {
PageSchemaController c = new PageSchemaController(mock(JdbcTemplate.class));
var resp = c.components();
assertEquals(HttpStatus.OK, resp.getStatusCode());
assertEquals(0, resp.getBody().get("status"));
assertTrue(resp.getBody().toString().contains("schemaVersion"));
assertTrue(resp.getBody().toString().contains("crud"));
}
@Test
@DisplayName("19. typed schema 校验端点拒绝未注册组件")
void validateSchemaRejectsUnsupportedComponent() {
PageSchemaController c = new PageSchemaController(mock(JdbcTemplate.class));
var resp = c.validateSchema("{\"type\":\"page\",\"body\":{\"type\":\"evil-widget\"}}");
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
assertEquals(1, resp.getBody().get("status"));
assertTrue(resp.getBody().toString().contains("UNSUPPORTED_COMPONENT"));
}
@Test
@DisplayName("20. PUT overlay 先做 typed schema 校验,失败时不写库")
void putOverlayRejectsUnsupportedComponentBeforeWrite() {
JdbcTemplate jdbc = mock(JdbcTemplate.class);
PageSchemaController c = new PageSchemaController(jdbc);
setAdminSession();
var resp = c.putOverlay(TID, "{\"type\":\"page\",\"body\":{\"type\":\"evil-widget\"}}");
assertEquals(HttpStatus.BAD_REQUEST, resp.getStatusCode());
assertTrue(resp.getBody().toString().contains("UNSUPPORTED_COMPONENT"));
verify(jdbc, never()).update(anyString(), any(), any(), any(), any(), any(), any());
clearSession();
}
// ── Session 工具 ─────────────────────────────────────────────────────────
private static void setAdminSession() {