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:
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user