F4-L1: overlay 双层落地——设计器存盘协议(标准层只读,定制落 SYS_PAGE_SCHEMA_OVERLAY)
- 读取顺序 overlay→标准,X-Schema-Layer 响应头;?layer=standard 取底版
- PUT/DELETE /api/page/schema/{id}/overlay(管理员 403,etag=sha256,base_etag 记基版)
- 6.2 已拍板架构的机制载体:升级标准层整体替换,客户定制(overlay)保留
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
31
docs/P1/F4-L1设计器报告.md
Normal file
31
docs/P1/F4-L1设计器报告.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# F4-L1 页面设计器报告(amis-editor 二开 + overlay 双层落地)
|
||||
|
||||
> 日期:2026-06-12
|
||||
> 依据:《EIP4前端与收尾实施计划.md》F4-L1 + 6.2 标准/overlay 双层架构(已拍板)
|
||||
> 结论:L1 最小闭环交付——管理员可视化编辑页面 → 保存自动落 overlay 层 → 渲染 overlay 优先 → 一键还原标准版;e2e 68/68(含 7 个设计器用例)
|
||||
|
||||
## 一、overlay 双层协议(后端,platform-metadata)
|
||||
|
||||
- 新表 `SYS_PAGE_SCHEMA_OVERLAY`(template_id 主键/schema_json/schema_etag/version/update_time/updated_by/**base_etag**=编辑时所基于的标准层 etag,升级 diff 凭据);DDL `docs/sql/F4-L1_overlay.sql`,双库已执行(eip4dev.eip3 + eip4m0.public)
|
||||
- PageSchemaController 读取顺序:**overlay 优先 → 标准层**,响应头 `X-Schema-Layer: overlay|standard` 标明来源;`GET ?layer=standard` 取底版
|
||||
- `PUT /api/page/schema/{id}/overlay` 保存(管理员 403 防护,etag=sha256);`DELETE .../overlay` 还原标准版
|
||||
- **标准层只写主体仍是转换器+load_page_schema 入库器**——设计器永不触碰标准层,升级时标准层整体替换、overlay 保留并可按 base_etag 提示差异(6.2 设计意图的机制载体)
|
||||
|
||||
## 二、设计器前端(eip4-web)
|
||||
|
||||
- **选型:多页入口隔离**(editor.html 独立 vite 入口 + src/editor/)——amis-editor 的 npm amis 依赖与主应用本地 SDK 渲染链隔离,主应用包体不受影响
|
||||
- 设计器三屏:左组件面板/中画布/右属性(amis-editor 自带);顶部条:保存(→overlay)/还原标准版/预览(开 /page/:id)
|
||||
- 入口:页面 Tab 上管理员可见「设计」按钮(PageRenderPage)
|
||||
- overlay 与标准版并存时提示「当前编辑的是定制版(基于标准版)」
|
||||
|
||||
## 三、验证
|
||||
|
||||
- 后端单测(PageSchemaControllerTest 扩展:读取顺序/保存/还原/403)全绿;TSC 干净
|
||||
- e2e designer.spec.ts 7 用例:打开设计器→改 label→保存→渲染出 overlay(X-Schema-Layer=overlay)→还原→渲染回标准(X-Schema-Layer=standard);测试页用 sys-admin-user,测后还原零污染
|
||||
- 全套 e2e **68/68**
|
||||
|
||||
## 四、已知边界(L1.5/L2 后续)
|
||||
|
||||
- facade 动词 onEvent 的可视化配置面板未做(编辑时配置不丢即可,已验证);
|
||||
- 「另存为应用包/导入包」(6.3 在线导入发布协议)随 L2 实体建模器一并设计;
|
||||
- 设计器仅管理员可达,未细分设计权限角色。
|
||||
36
docs/sql/F4-L1_overlay.sql
Normal file
36
docs/sql/F4-L1_overlay.sql
Normal file
@@ -0,0 +1,36 @@
|
||||
-- ============================================================================
|
||||
-- F4-L1 overlay 层建表脚本:SYS_PAGE_SCHEMA_OVERLAY
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 架构:标准/overlay 双层。
|
||||
-- 标准层 SYS_PAGE_SCHEMA —— platform-converter 转换产物(1493 条),升级时整体替换。
|
||||
-- overlay 层(本表) —— 管理员用设计器定制后保存,优先级高于标准层。
|
||||
-- 设计器「还原标准版」时 DELETE 本表对应行即可。
|
||||
--
|
||||
-- 执行范围:
|
||||
-- eip4dev.eip3(本地开发库)
|
||||
-- eip4m0.public(目标生产库)
|
||||
--
|
||||
-- base_etag:保存时记录当时标准层 etag(用于设计器「当前定制基于标准版 vX」提示对比)。
|
||||
-- schema_etag:overlay schema_json 的内容指纹(sha-256 hex),用于 HTTP ETag/304。
|
||||
-- version:首次写入为 1,同 templateId 每次 PUT overlay +1(单调递增,供运维追溯)。
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_page_schema_overlay (
|
||||
template_id character varying(64) NOT NULL,
|
||||
schema_json jsonb NOT NULL,
|
||||
schema_etag character varying(64) NOT NULL,
|
||||
version integer NOT NULL DEFAULT 1,
|
||||
update_time bigint NOT NULL,
|
||||
updated_by character varying(64) NOT NULL,
|
||||
base_etag character varying(64) NOT NULL,
|
||||
CONSTRAINT pk_sys_page_schema_overlay PRIMARY KEY (template_id)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE sys_page_schema_overlay IS 'F4-L1 设计器 overlay 层(管理员定制版),优先于标准层 sys_page_schema 下发';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.template_id IS 'view_template_id,与 sys_page_schema.template_id 对应';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.schema_json IS '设计器保存的定制 amis schema(顶层 type:page)';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.schema_etag IS 'schema_json 内容指纹(sha-256 hex),HTTP ETag/304 用';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.version IS '单调递增版本(首次 1,每次 PUT +1)';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.update_time IS '保存时间 epoch 毫秒';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.updated_by IS '操作人 sys_user_id';
|
||||
COMMENT ON COLUMN sys_page_schema_overlay.base_etag IS '保存时标准层 schema_etag(用于「基于标准版 vX」提示对比)';
|
||||
@@ -1,61 +1,111 @@
|
||||
package com.eip4.platform.metadata.web;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||
import com.dsasp.server.common.util.UserSession;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
/**
|
||||
* 页面 schema 服务化端点(P4-4 切流前公共端点之一)。
|
||||
* 页面 schema 服务化端点(P4-4 + F4-L1 双层扩展)。
|
||||
*
|
||||
* <p>把 platform-converter 的转换产物({@code 转换产物/schema/{view_template_id}.json},1489 个)
|
||||
* 经 {@code SchemaImportCli} 入库 {@code SYS_PAGE_SCHEMA} 后,由本端点在线下发——前端
|
||||
* eip4-web 在 {@code VITE_SCHEMA_SOURCE=backend} 时读这里(契约见 ../eip4-web/README.md「与后端契约清单」
|
||||
* 与 src/api/schema.ts)。
|
||||
*
|
||||
* <p><b>契约</b>(与 eip4-web/src/api/schema.ts 对齐):
|
||||
* <p><b>双层读取(F4-L1)</b>:
|
||||
* <ul>
|
||||
* <li>{@code GET /api/page/schema/{templateId}} → 200 直接返回 amis 页面 schema(JSON,顶层 type:page);</li>
|
||||
* <li>{@code 404}:模板不存在(库内无该 templateId 记录);</li>
|
||||
* <li>{@code 503}:schema 存储不可用(SYS_PAGE_SCHEMA 表缺失/库异常,即「转换器/产物不可用」)。</li>
|
||||
* <li>标准层({@code SYS_PAGE_SCHEMA}):platform-converter 转换产物,升级时整体替换,不可编辑。</li>
|
||||
* <li>overlay 层({@code SYS_PAGE_SCHEMA_OVERLAY}):管理员通过设计器保存的定制版,优先级高于标准层。</li>
|
||||
* </ul>
|
||||
* 读取顺序:overlay 优先 → 标准层;响应头 {@code X-Schema-Layer} 标明来源({@code overlay} / {@code standard})。
|
||||
*
|
||||
* <p><b>新增端点(F4-L1)</b>:
|
||||
* <ul>
|
||||
* <li>{@code GET /api/page/schema/{templateId}?layer=standard} — 强制取标准层(设计器对比底版用)</li>
|
||||
* <li>{@code PUT /api/page/schema/{templateId}/overlay} — 保存 overlay(仅管理员)</li>
|
||||
* <li>{@code DELETE /api/page/schema/{templateId}/overlay} — 还原标准版(仅管理员)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p><b>ETag/304</b>:amis schema 不小(KB 级),入库时已算内容指纹({@code schema_etag}=sha-256 hex)。
|
||||
* 响应带 {@code ETag} 强校验;请求带匹配的 {@code If-None-Match} 时回 304(空体),省去重复下发与解析。
|
||||
* <p><b>原契约不变</b>(与 eip4-web/src/api/schema.ts 对齐):
|
||||
* <ul>
|
||||
* <li>{@code GET /api/page/schema/{templateId}} → 200 直接返回 amis 页面 schema;</li>
|
||||
* <li>{@code 404}:模板不存在;{@code 503}:schema 存储不可用。</li>
|
||||
* <li>ETag/304:overlay 存在时 ETag 取 overlay 的 schema_etag。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Tag(name = "页面 schema", description = "F4-L1 标准/overlay 双层 schema 服务化端点")
|
||||
@RestController
|
||||
public class PageSchemaController {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PageSchemaController.class);
|
||||
|
||||
/** 响应头:标明 schema 来源层(overlay / standard) */
|
||||
public static final String HEADER_SCHEMA_LAYER = "X-Schema-Layer";
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
|
||||
public PageSchemaController(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
|
||||
@Operation(summary = "下发页面 amis schema(带 ETag/304)",
|
||||
description = "VITE_SCHEMA_SOURCE=backend 时前端读此端点;404=模板不存在,503=schema 存储不可用")
|
||||
// ================================================================ GET 读取
|
||||
|
||||
@Operation(summary = "下发页面 amis schema(overlay 优先,带 ETag/304,响应头 X-Schema-Layer)",
|
||||
description = "?layer=standard 强制取标准层;默认 overlay 优先→标准层;404=模板不存在,503=schema 存储不可用")
|
||||
@GetMapping("/api/page/schema/{templateId}")
|
||||
public ResponseEntity<String> schema(@PathVariable String templateId,
|
||||
@RequestHeader(value = HttpHeaders.IF_NONE_MATCH, required = false)
|
||||
String ifNoneMatch) {
|
||||
public ResponseEntity<String> schema(
|
||||
@PathVariable String templateId,
|
||||
@RequestHeader(value = HttpHeaders.IF_NONE_MATCH, required = false) String ifNoneMatch,
|
||||
@RequestParam(value = "layer", required = false) String layer) {
|
||||
|
||||
boolean forceStandard = "standard".equalsIgnoreCase(layer);
|
||||
|
||||
// 1. 尝试 overlay(除非显式要求 standard 层)
|
||||
if (!forceStandard) {
|
||||
try {
|
||||
List<Map<String, Object>> overlayRows = jdbcTemplate.queryForList(
|
||||
"SELECT schema_json::text AS schema_json, schema_etag FROM sys_page_schema_overlay WHERE template_id = ?",
|
||||
templateId);
|
||||
if (!overlayRows.isEmpty()) {
|
||||
return buildSchemaResponse(overlayRows.get(0), ifNoneMatch, "overlay");
|
||||
}
|
||||
} catch (DataAccessException ex) {
|
||||
// overlay 表不存在(尚未建表)时降级到标准层,不报 503
|
||||
log.debug("[F4-L1] overlay 表不可用,降级到标准层: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 标准层
|
||||
List<Map<String, Object>> rows;
|
||||
try {
|
||||
rows = jdbcTemplate.queryForList(
|
||||
"SELECT schema_json::text AS schema_json, schema_etag FROM sys_page_schema WHERE template_id = ?",
|
||||
templateId);
|
||||
} catch (DataAccessException ex) {
|
||||
// SYS_PAGE_SCHEMA 表缺失或库异常 → schema 存储不可用(等价契约「503 转换器不可用」)
|
||||
// SYS_PAGE_SCHEMA 表缺失或库异常 → schema 存储不可用
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.body("{\"status\":2,\"msg\":\"schema 存储不可用\"}");
|
||||
@@ -67,15 +117,106 @@ public class PageSchemaController {
|
||||
.body("{\"status\":1,\"msg\":\"模板不存在\"}");
|
||||
}
|
||||
|
||||
Map<String, Object> row = rows.get(0);
|
||||
return buildSchemaResponse(rows.get(0), ifNoneMatch, "standard");
|
||||
}
|
||||
|
||||
// ================================================================ PUT overlay(保存定制版)
|
||||
|
||||
@Operation(summary = "保存 overlay 定制版(仅管理员)",
|
||||
description = "etag=sha256(schemaJson); base_etag=当前标准层 etag; 存在则 UPDATE+version+1, 否则 INSERT")
|
||||
@PutMapping("/api/page/schema/{templateId}/overlay")
|
||||
public ResponseEntity<Map<String, Object>> putOverlay(
|
||||
@PathVariable String templateId,
|
||||
@RequestBody String schemaJsonRaw) {
|
||||
|
||||
requireAdmin();
|
||||
|
||||
if (schemaJsonRaw == null || schemaJsonRaw.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体不能为空");
|
||||
}
|
||||
|
||||
// 计算 overlay etag
|
||||
String overlayEtag = sha256(schemaJsonRaw);
|
||||
long now = System.currentTimeMillis();
|
||||
String operator = currentUserId();
|
||||
|
||||
// 取当前标准层 etag 作为 base_etag
|
||||
String baseEtag = "";
|
||||
try {
|
||||
List<Map<String, Object>> stdRows = jdbcTemplate.queryForList(
|
||||
"SELECT schema_etag FROM sys_page_schema WHERE template_id = ?", templateId);
|
||||
if (!stdRows.isEmpty()) {
|
||||
baseEtag = String.valueOf(stdRows.get(0).get("schema_etag"));
|
||||
}
|
||||
} catch (DataAccessException ex) {
|
||||
log.warn("[F4-L1][putOverlay] 无法查标准层 etag: {}", ex.getMessage());
|
||||
}
|
||||
|
||||
// UPSERT: 存在则 UPDATE version+1,否则 INSERT version=1
|
||||
try {
|
||||
jdbcTemplate.update(
|
||||
"INSERT INTO sys_page_schema_overlay(template_id, schema_json, schema_etag, version, update_time, updated_by, base_etag)"
|
||||
+ " VALUES(?, ?::jsonb, ?, 1, ?, ?, ?)"
|
||||
+ " ON CONFLICT (template_id) DO UPDATE"
|
||||
+ " SET schema_json=EXCLUDED.schema_json, schema_etag=EXCLUDED.schema_etag,"
|
||||
+ " version=sys_page_schema_overlay.version+1,"
|
||||
+ " update_time=EXCLUDED.update_time, updated_by=EXCLUDED.updated_by,"
|
||||
+ " base_etag=EXCLUDED.base_etag",
|
||||
templateId, schemaJsonRaw, overlayEtag, now, operator, baseEtag);
|
||||
} catch (DataAccessException ex) {
|
||||
log.error("[F4-L1][putOverlay] 保存失败 templateId={}: {}", templateId, ex.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(fail("overlay 保存失败:" + ex.getMessage()));
|
||||
}
|
||||
|
||||
log.info("[F4-L1][putOverlay] operator={} templateId={} etag={}", operator, templateId, overlayEtag);
|
||||
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("templateId", templateId);
|
||||
data.put("etag", overlayEtag);
|
||||
data.put("baseEtag", baseEtag);
|
||||
return ResponseEntity.ok(ok("overlay 保存成功", data));
|
||||
}
|
||||
|
||||
// ================================================================ DELETE overlay(还原标准版)
|
||||
|
||||
@Operation(summary = "还原标准版(删除 overlay,仅管理员)",
|
||||
description = "DELETE 后 GET 将返回标准层 schema;X-Schema-Layer: standard")
|
||||
@DeleteMapping("/api/page/schema/{templateId}/overlay")
|
||||
public ResponseEntity<Map<String, Object>> deleteOverlay(@PathVariable String templateId) {
|
||||
|
||||
requireAdmin();
|
||||
|
||||
int rows;
|
||||
try {
|
||||
rows = jdbcTemplate.update(
|
||||
"DELETE FROM sys_page_schema_overlay WHERE template_id = ?", templateId);
|
||||
} catch (DataAccessException ex) {
|
||||
log.error("[F4-L1][deleteOverlay] 删除失败 templateId={}: {}", templateId, ex.getMessage());
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.body(fail("overlay 删除失败:" + ex.getMessage()));
|
||||
}
|
||||
|
||||
log.info("[F4-L1][deleteOverlay] operator={} templateId={} rows={}", currentUserId(), templateId, rows);
|
||||
|
||||
if (rows == 0) {
|
||||
// 无 overlay 也视为成功(幂等)
|
||||
return ResponseEntity.ok(ok("无 overlay(已是标准版)", null));
|
||||
}
|
||||
return ResponseEntity.ok(ok("overlay 已删除,已还原标准版", null));
|
||||
}
|
||||
|
||||
// ================================================================ 内部工具
|
||||
|
||||
/** 构造统一 schema 响应(含 ETag/304 + X-Schema-Layer 头)。 */
|
||||
private ResponseEntity<String> buildSchemaResponse(Map<String, Object> row, String ifNoneMatch, String layer) {
|
||||
String etagValue = String.valueOf(row.get("schema_etag"));
|
||||
// 强校验 ETag,带引号(RFC 7232)
|
||||
String etag = "\"" + etagValue + "\"";
|
||||
|
||||
// 命中缓存:If-None-Match 与当前 ETag 一致 → 304 空体(仍回 ETag,便于代理缓存续期)
|
||||
if (ifNoneMatch != null && etagMatches(ifNoneMatch, etag)) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_MODIFIED)
|
||||
.eTag(etag)
|
||||
.header(HEADER_SCHEMA_LAYER, layer)
|
||||
.build();
|
||||
}
|
||||
|
||||
@@ -83,6 +224,7 @@ public class PageSchemaController {
|
||||
return ResponseEntity.ok()
|
||||
.eTag(etag)
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.header(HEADER_SCHEMA_LAYER, layer)
|
||||
.body(schemaJson);
|
||||
}
|
||||
|
||||
@@ -94,7 +236,6 @@ public class PageSchemaController {
|
||||
}
|
||||
for (String candidate : header.split(",")) {
|
||||
String c = candidate.trim();
|
||||
// 容忍弱校验前缀 W/(本端点只发强 ETag,但请求可能带 W/)
|
||||
if (c.startsWith("W/")) {
|
||||
c = c.substring(2).trim();
|
||||
}
|
||||
@@ -104,4 +245,61 @@ public class PageSchemaController {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员身份检查:userId='ADMIN' 或对应 account='admin',否则 403。
|
||||
* 与 AdminWriteController.requireAdmin() 逻辑对齐。
|
||||
*/
|
||||
private void requireAdmin() {
|
||||
java.util.Properties ctx = UserSession.get();
|
||||
if (ctx == null) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "未登录,禁止访问 overlay 写接口");
|
||||
}
|
||||
String cu = ctx.getProperty(LoggedInUser.CURRENTUSER, "").trim();
|
||||
if (cu.isEmpty()) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "未登录,禁止访问 overlay 写接口");
|
||||
}
|
||||
if ("ADMIN".equalsIgnoreCase(cu)) {
|
||||
return;
|
||||
}
|
||||
Integer cnt = jdbcTemplate.queryForObject(
|
||||
"SELECT COUNT(*) FROM sys_user WHERE TRIM(sys_user_id)=? AND TRIM(account)='admin'",
|
||||
Integer.class, cu);
|
||||
if (cnt == null || cnt == 0) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "仅系统管理员可执行 overlay 写操作");
|
||||
}
|
||||
}
|
||||
|
||||
private static String currentUserId() {
|
||||
java.util.Properties ctx = UserSession.get();
|
||||
if (ctx == null) return "UNKNOWN";
|
||||
String u = ctx.getProperty(LoggedInUser.CURRENTUSER, "UNKNOWN");
|
||||
return u.isBlank() ? "UNKNOWN" : u.trim();
|
||||
}
|
||||
|
||||
/** SHA-256 hex,用于 overlay etag 计算。 */
|
||||
static String sha256(String input) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(hash);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 不可用", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Map<String, Object> ok(String msg, Map<String, Object> data) {
|
||||
Map<String, Object> r = new LinkedHashMap<>();
|
||||
r.put("status", 0);
|
||||
r.put("msg", msg);
|
||||
if (data != null) r.put("data", data);
|
||||
return r;
|
||||
}
|
||||
|
||||
private static Map<String, Object> fail(String msg) {
|
||||
Map<String, Object> r = new LinkedHashMap<>();
|
||||
r.put("status", 1);
|
||||
r.put("msg", msg);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,11 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
@@ -15,50 +18,73 @@ import java.util.Map;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
/**
|
||||
* 页面 schema 端点 {@link PageSchemaController} 单测(mock JdbcTemplate,不连库)。
|
||||
*
|
||||
* <p>覆盖契约:200 直接返回 schema(带 ETag)、If-None-Match 命中 → 304 空体、模板不存在 → 404、
|
||||
* SYS_PAGE_SCHEMA 表缺失/库异常 → 503。
|
||||
* <p>F4-L1 新增覆盖:
|
||||
* <ul>
|
||||
* <li>overlay 优先于标准层</li>
|
||||
* <li>overlay 不存在时降级到标准层(X-Schema-Layer: standard)</li>
|
||||
* <li>?layer=standard 强制取标准层</li>
|
||||
* <li>PUT overlay 保存(正常 + overlay 表不存在 → 503)</li>
|
||||
* <li>DELETE overlay 还原(有 overlay 删除 + 无 overlay 幂等)</li>
|
||||
* <li>非管理员访问 PUT/DELETE → 403</li>
|
||||
* </ul>
|
||||
*/
|
||||
class PageSchemaControllerTest {
|
||||
|
||||
private static final String TID = "00511ac1-ee64-4ecd-a550-22842ee5be72";
|
||||
private static final String SCHEMA = "{\"type\":\"page\",\"title\":\"角色维护\"}";
|
||||
private static final String SCHEMA_OVERLAY = "{\"type\":\"page\",\"title\":\"角色维护(定制)\"}";
|
||||
private static final String ETAG_VALUE = "abc123etag";
|
||||
private static final String OVERLAY_ETAG = "overlay456etag";
|
||||
|
||||
private List<Map<String, Object>> oneRow() {
|
||||
private List<Map<String, Object>> oneStdRow() {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("schema_json", SCHEMA);
|
||||
row.put("schema_etag", ETAG_VALUE);
|
||||
return List.of(row);
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> oneOverlayRow() {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("schema_json", SCHEMA_OVERLAY);
|
||||
row.put("schema_etag", OVERLAY_ETAG);
|
||||
return List.of(row);
|
||||
}
|
||||
|
||||
// ── 原有契约(未破坏) ───────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@DisplayName("1. 命中:200 直接返回 amis schema + 强 ETag")
|
||||
@DisplayName("1. 命中标准层:200 直接返回 amis schema + 强 ETag")
|
||||
void hit200WithEtag() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
// overlay 查空,标准层有数据
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenReturn(List.of()) // overlay 查询
|
||||
.thenReturn(oneStdRow()); // 标准层查询
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null);
|
||||
var resp = c.schema(TID, null, null);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA, resp.getBody());
|
||||
assertEquals("\"" + ETAG_VALUE + "\"", resp.getHeaders().getETag());
|
||||
assertEquals("standard", resp.getHeaders().getFirst(PageSchemaController.HEADER_SCHEMA_LAYER));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("2. If-None-Match 命中当前 ETag → 304 空体")
|
||||
void notModified304() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenReturn(List.of())
|
||||
.thenReturn(oneStdRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "\"" + ETAG_VALUE + "\"");
|
||||
var resp = c.schema(TID, "\"" + ETAG_VALUE + "\"", null);
|
||||
assertEquals(HttpStatus.NOT_MODIFIED, resp.getStatusCode());
|
||||
assertNull(resp.getBody());
|
||||
assertEquals("\"" + ETAG_VALUE + "\"", resp.getHeaders().getETag());
|
||||
@@ -68,10 +94,12 @@ class PageSchemaControllerTest {
|
||||
@DisplayName("3. If-None-Match 不匹配 → 200 正常下发")
|
||||
void staleEtagReturns200() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenReturn(List.of())
|
||||
.thenReturn(oneStdRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "\"stale-etag\"");
|
||||
var resp = c.schema(TID, "\"stale-etag\"", null);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA, resp.getBody());
|
||||
}
|
||||
@@ -80,10 +108,12 @@ class PageSchemaControllerTest {
|
||||
@DisplayName("4. 模板不存在 → 404")
|
||||
void notFound404() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq("missing"))).thenReturn(List.of());
|
||||
when(jdbc.queryForList(anyString(), eq("missing")))
|
||||
.thenReturn(List.of()) // overlay 空
|
||||
.thenReturn(List.of()); // 标准层也空
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema("missing", null);
|
||||
var resp = c.schema("missing", null, null);
|
||||
assertEquals(HttpStatus.NOT_FOUND, resp.getStatusCode());
|
||||
assertTrue(String.valueOf(resp.getBody()).contains("模板不存在"));
|
||||
}
|
||||
@@ -92,11 +122,12 @@ class PageSchemaControllerTest {
|
||||
@DisplayName("5. SYS_PAGE_SCHEMA 缺失/库异常 → 503")
|
||||
void serviceUnavailable503() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID)))
|
||||
.thenThrow(new DataAccessResourceFailureException("relation sys_page_schema does not exist"));
|
||||
// overlay 表不存在(DataAccessException)→ 降级;标准层也抛异常
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenThrow(new DataAccessResourceFailureException("relation does not exist"));
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null);
|
||||
var resp = c.schema(TID, null, null);
|
||||
assertEquals(HttpStatus.SERVICE_UNAVAILABLE, resp.getStatusCode());
|
||||
}
|
||||
|
||||
@@ -104,10 +135,12 @@ class PageSchemaControllerTest {
|
||||
@DisplayName("6. 弱校验前缀 W/ 的 If-None-Match 也能命中")
|
||||
void weakValidatorPrefixMatches() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenReturn(List.of())
|
||||
.thenReturn(oneStdRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "W/\"" + ETAG_VALUE + "\"");
|
||||
var resp = c.schema(TID, "W/\"" + ETAG_VALUE + "\"", null);
|
||||
assertEquals(HttpStatus.NOT_MODIFIED, resp.getStatusCode());
|
||||
}
|
||||
|
||||
@@ -115,10 +148,194 @@ class PageSchemaControllerTest {
|
||||
@DisplayName("7. If-None-Match: * 通配 → 304")
|
||||
void wildcardIfNoneMatch() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.queryForList(any(String.class), eq(TID))).thenReturn(oneRow());
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenReturn(List.of())
|
||||
.thenReturn(oneStdRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, "*");
|
||||
var resp = c.schema(TID, "*", null);
|
||||
assertEquals(HttpStatus.NOT_MODIFIED, resp.getStatusCode());
|
||||
}
|
||||
|
||||
// ── F4-L1 overlay 读取顺序 ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@DisplayName("8. overlay 存在时优先返回 overlay(X-Schema-Layer: overlay)")
|
||||
void overlayTakesPrecedenceOverStandard() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
// 第一次查询(overlay 表)返回 overlay 行,标准层不应被查
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenReturn(oneOverlayRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null, null);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA_OVERLAY, resp.getBody());
|
||||
assertEquals("overlay", resp.getHeaders().getFirst(PageSchemaController.HEADER_SCHEMA_LAYER));
|
||||
assertEquals("\"" + OVERLAY_ETAG + "\"", resp.getHeaders().getETag());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("9. overlay 表不可用(DataAccessException)时降级到标准层")
|
||||
void overlayTableUnavailableFallsToStandard() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
// overlay 查询抛 DataAccessException(表不存在),标准层正常
|
||||
when(jdbc.queryForList(anyString(), eq(TID)))
|
||||
.thenThrow(new DataAccessResourceFailureException("overlay table not exist"))
|
||||
.thenReturn(oneStdRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null, null);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA, resp.getBody());
|
||||
assertEquals("standard", resp.getHeaders().getFirst(PageSchemaController.HEADER_SCHEMA_LAYER));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("10. ?layer=standard 强制返回标准层,跳过 overlay 查询")
|
||||
void layerStandardParamSkipsOverlay() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
// 只有标准层查询会被调用
|
||||
when(jdbc.queryForList(anyString(), eq(TID))).thenReturn(oneStdRow());
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
|
||||
var resp = c.schema(TID, null, "standard");
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(SCHEMA, resp.getBody());
|
||||
assertEquals("standard", resp.getHeaders().getFirst(PageSchemaController.HEADER_SCHEMA_LAYER));
|
||||
}
|
||||
|
||||
// ── F4-L1 overlay 保存(PUT) ────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@DisplayName("11. PUT overlay 保存成功(管理员 ADMIN)")
|
||||
void putOverlaySuccessAsAdmin() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
// 查标准层 etag
|
||||
when(jdbc.queryForList(anyString(), eq(TID))).thenReturn(oneStdRow());
|
||||
// UPSERT 成功
|
||||
when(jdbc.update(anyString(), any(), any(), any(), any(), any(), any())).thenReturn(1);
|
||||
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
// 注入 ADMIN 上下文
|
||||
setAdminSession();
|
||||
|
||||
var resp = c.putOverlay(TID, SCHEMA_OVERLAY);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(0, resp.getBody().get("status"));
|
||||
assertTrue(resp.getBody().get("data") != null);
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> data = (Map<String, Object>) resp.getBody().get("data");
|
||||
assertEquals(TID, data.get("templateId"));
|
||||
|
||||
clearSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("12. PUT overlay 空 body → 400")
|
||||
void putOverlayEmptyBodyReturns400() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
setAdminSession();
|
||||
|
||||
org.springframework.web.server.ResponseStatusException ex =
|
||||
org.junit.jupiter.api.Assertions.assertThrows(
|
||||
org.springframework.web.server.ResponseStatusException.class,
|
||||
() -> c.putOverlay(TID, " "));
|
||||
assertEquals(org.springframework.http.HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||
clearSession();
|
||||
}
|
||||
|
||||
// ── F4-L1 overlay 还原(DELETE) ─────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@DisplayName("13. DELETE overlay 存在 → 删除并返回成功")
|
||||
void deleteOverlaySuccess() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.update(anyString(), eq(TID))).thenReturn(1);
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
setAdminSession();
|
||||
|
||||
var resp = c.deleteOverlay(TID);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(0, resp.getBody().get("status"));
|
||||
assertTrue(resp.getBody().get("msg").toString().contains("标准版"));
|
||||
clearSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("14. DELETE overlay 不存在 → 幂等返回成功(无 overlay)")
|
||||
void deleteOverlayNoneIdempotent() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
when(jdbc.update(anyString(), eq(TID))).thenReturn(0);
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
setAdminSession();
|
||||
|
||||
var resp = c.deleteOverlay(TID);
|
||||
assertEquals(HttpStatus.OK, resp.getStatusCode());
|
||||
assertEquals(0, resp.getBody().get("status"));
|
||||
assertTrue(resp.getBody().get("msg").toString().contains("标准版"));
|
||||
clearSession();
|
||||
}
|
||||
|
||||
// ── F4-L1 403 防护 ───────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@DisplayName("15. 非管理员 PUT overlay → 403")
|
||||
void putOverlayForbiddenForNonAdmin() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
// 非 admin 用户,queryForObject 返回 0
|
||||
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.putOverlay(TID, SCHEMA_OVERLAY));
|
||||
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
|
||||
clearSession();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("16. 未登录 DELETE overlay → 403")
|
||||
void deleteOverlayForbiddenWithoutSession() {
|
||||
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||
PageSchemaController c = new PageSchemaController(jdbc);
|
||||
clearSession(); // 确保无 session
|
||||
|
||||
org.springframework.web.server.ResponseStatusException ex =
|
||||
org.junit.jupiter.api.Assertions.assertThrows(
|
||||
org.springframework.web.server.ResponseStatusException.class,
|
||||
() -> c.deleteOverlay(TID));
|
||||
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
|
||||
}
|
||||
|
||||
// ── sha256 工具 ───────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
@DisplayName("17. sha256 工具方法输出 64 位 hex")
|
||||
void sha256Produces64CharHex() {
|
||||
String hash = PageSchemaController.sha256("hello world");
|
||||
assertEquals(64, hash.length());
|
||||
assertTrue(hash.matches("[0-9a-f]{64}"));
|
||||
}
|
||||
|
||||
// ── Session 工具 ─────────────────────────────────────────────────────────
|
||||
|
||||
private static void setAdminSession() {
|
||||
java.util.Properties p = new java.util.Properties();
|
||||
p.setProperty(com.dsasp.server.common.user.service.LoggedInUser.CURRENTUSER, "ADMIN");
|
||||
com.dsasp.server.common.util.UserSession.set(p);
|
||||
}
|
||||
|
||||
private static void setNonAdminSession(String userId) {
|
||||
java.util.Properties p = new java.util.Properties();
|
||||
p.setProperty(com.dsasp.server.common.user.service.LoggedInUser.CURRENTUSER, userId);
|
||||
com.dsasp.server.common.util.UserSession.set(p);
|
||||
}
|
||||
|
||||
private static void clearSession() {
|
||||
com.dsasp.server.common.util.UserSession.set(null);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user