feat(testing): 保存共享分析参数及私有截图证据

This commit is contained in:
zhanghao 2026-11-30 15:48:27 +08:00
parent b7ec600aae
commit 00d592b368
10 changed files with 557 additions and 0 deletions

View File

@ -86,3 +86,4 @@
- Ruling: 在用户现有 `project` 开发分支落地代码,隔离副本执行后端构建 — 用户持续要求本地项目修改且已有依赖,不引入分支切换或依赖安装 — 验证副本不能替代实际库升级,交付会明确此限制。
- 设计审查:nothing important left;已修正 AC-005 对轮次新增列的文案冲突。
- Task 1:新 API 缺失的编译 RED 已观察;实现后 5 个规则/识别/HTTP 用例全部通过;既有标定后端 22、前端 11 用例基线通过。验证在隔离副本,不触发运行服务加载。
- Task 2:共享资料/Mapper/存储 API 缺失的 RED 已观察;实现后累计 17 个相关用例通过,覆盖真实 H2 DDL/分页/乐观锁、只读拒写、错模式、模型后资格撤销和共享存储命名空间。005 仅生成,未连接真实数据库执行。

View File

@ -130,6 +130,7 @@ CREATE TABLE IF NOT EXISTS tm_test_run (
config_id BIGINT NOT NULL COMMENT '冻结的任务配置版本',
robot_snapshot_json LONGTEXT NOT NULL COMMENT '被测和对比机器人信息快照',
calibration_json LONGTEXT NOT NULL COMMENT '关联的标定版本及内容快照',
analysis_parameters_json LONGTEXT NULL COMMENT '创建轮次时选用的共享分析参数快照,不回写资料后续编辑',
actual_at VARCHAR(32) COMMENT '操作人确认的实际试验本地时间ISO格式,不以上传时间代替',
notes TEXT COMMENT '本轮试验说明',
created_by BIGINT NOT NULL COMMENT '发起本轮测试的用户ID',
@ -325,3 +326,53 @@ CREATE TABLE IF NOT EXISTS tm_calibration_image (
CONSTRAINT fk_tm_cal_image_robot FOREIGN KEY(robot_id) REFERENCES tm_robot(id),
CONSTRAINT fk_tm_cal_image_actor FOREIGN KEY(created_by) REFERENCES sys_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='标定区域截图证据,原图不可变';
-- 新安装同时具备共享分析参数;既有安装使用005增量,资料不参与测试计算。
CREATE TABLE IF NOT EXISTS tm_analysis_parameter_image (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '共享分析参数截图主键',
mode VARCHAR(20) NOT NULL COMMENT 'TRAJECTORY轨迹或POSE位姿',
name VARCHAR(255) NOT NULL COMMENT '原始文件名,仅显示',
media_type VARCHAR(30) NOT NULL COMMENT '真实PNG/JPEG类型',
object_key VARCHAR(700) NOT NULL COMMENT '私有对象键,不对外返回',
sha256 CHAR(64) NOT NULL COMMENT '服务器计算的原图摘要',
size BIGINT NOT NULL COMMENT '原图字节数',
width INT NOT NULL COMMENT '原图宽度',
height INT NOT NULL COMMENT '原图高度',
recognition_json LONGTEXT NULL COMMENT '通过固定字段校验的识别候选,不自动保存资料',
created_by BIGINT NOT NULL COMMENT '上传人',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
PRIMARY KEY(id),
UNIQUE KEY uk_tm_analysis_image(mode,sha256),
CONSTRAINT fk_tm_analysis_image_actor FOREIGN KEY(created_by) REFERENCES sys_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='共享分析参数原始截图,无项目或设备关联';
CREATE TABLE IF NOT EXISTS tm_analysis_parameter (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '共享分析参数资料主键',
name VARCHAR(120) NOT NULL COMMENT '资料名称',
mode VARCHAR(20) NOT NULL COMMENT 'TRAJECTORY轨迹或POSE位姿',
data_json LONGTEXT NOT NULL COMMENT '当前模式固定字段,仅字符串数值及速度参照段文本',
image_id BIGINT NOT NULL COMMENT '当前原图,替换不删除旧原图',
version BIGINT NOT NULL DEFAULT 1 COMMENT '共享资料编辑及轮次选择的乐观锁版本',
created_by BIGINT NOT NULL COMMENT '创建人',
updated_by BIGINT NOT NULL COMMENT '最近编辑人',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近编辑时间',
PRIMARY KEY(id),
KEY ix_tm_analysis_parameter_mode(mode,updated_at,id),
CONSTRAINT fk_tm_analysis_parameter_image FOREIGN KEY(image_id) REFERENCES tm_analysis_parameter_image(id),
CONSTRAINT fk_tm_analysis_parameter_creator FOREIGN KEY(created_by) REFERENCES sys_user(user_id),
CONSTRAINT fk_tm_analysis_parameter_editor FOREIGN KEY(updated_by) REFERENCES sys_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='独立共享分析参数资料,仅存储不参与测试计算';
-- 只向已有测试读取角色补充新页面,不给普通用户添加测试资格或写权限。
SET @tm_analysis_parent=(SELECT menu_id FROM sys_menu WHERE parent_id=0 AND path='testing' LIMIT 1);
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,route_name,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
SELECT '分析参数',@tm_analysis_parent,6,'analysis-parameters','testing/analysisParameters/index','TestingAnalysisParameters',1,1,'C','0','0','testing:read','chart','admin',CURRENT_TIMESTAMP
WHERE @tm_analysis_parent IS NOT NULL AND NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@tm_analysis_parent AND path='analysis-parameters');
INSERT INTO sys_role_menu(role_id,menu_id)
SELECT DISTINCT source.role_id,target.menu_id FROM sys_role_menu source
JOIN sys_menu readable ON readable.menu_id=source.menu_id
JOIN sys_role role_record ON role_record.role_id=source.role_id
JOIN sys_menu target ON target.parent_id=@tm_analysis_parent AND target.path='analysis-parameters'
WHERE readable.parent_id=@tm_analysis_parent AND readable.perms='testing:read'
AND role_record.del_flag='0' AND NOT EXISTS(SELECT 1 FROM sys_role_menu existing WHERE existing.role_id=source.role_id AND existing.menu_id=target.menu_id);

View File

@ -0,0 +1,64 @@
-- 分析参数共享资料库增量升级。先备份并确认目标库,001及已有升级脚本之后、新后端启动前执行。
-- 只新增两张资料表、轮次可空快照列及菜单;不删除历史数据,不重算判定,不关联项目或设备。
-- MySQL DDL 隐式提交,回退应用仍保留新增结构及已保存快照,禁止通过删列回退。
SET NAMES utf8mb4;
CREATE TABLE IF NOT EXISTS tm_analysis_parameter_image (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '共享分析参数截图主键',
mode VARCHAR(20) NOT NULL COMMENT 'TRAJECTORY轨迹或POSE位姿',
name VARCHAR(255) NOT NULL COMMENT '原始文件名,仅显示',
media_type VARCHAR(30) NOT NULL COMMENT '真实PNG/JPEG类型',
object_key VARCHAR(700) NOT NULL COMMENT '私有对象键,不对外返回',
sha256 CHAR(64) NOT NULL COMMENT '服务器计算的原图摘要',
size BIGINT NOT NULL COMMENT '原图字节数',
width INT NOT NULL COMMENT '原图宽度',
height INT NOT NULL COMMENT '原图高度',
recognition_json LONGTEXT NULL COMMENT '通过固定字段校验的识别候选,不自动保存资料',
created_by BIGINT NOT NULL COMMENT '上传人',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
PRIMARY KEY(id),
UNIQUE KEY uk_tm_analysis_image(mode,sha256),
CONSTRAINT fk_tm_analysis_image_actor FOREIGN KEY(created_by) REFERENCES sys_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='共享分析参数原始截图,无项目或设备关联';
CREATE TABLE IF NOT EXISTS tm_analysis_parameter (
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '共享分析参数资料主键',
name VARCHAR(120) NOT NULL COMMENT '资料名称',
mode VARCHAR(20) NOT NULL COMMENT 'TRAJECTORY轨迹或POSE位姿',
data_json LONGTEXT NOT NULL COMMENT '当前模式固定字段,仅字符串数值及速度参照段文本',
image_id BIGINT NOT NULL COMMENT '当前原图,替换不删除旧原图',
version BIGINT NOT NULL DEFAULT 1 COMMENT '共享资料编辑及轮次选择的乐观锁版本',
created_by BIGINT NOT NULL COMMENT '创建人',
updated_by BIGINT NOT NULL COMMENT '最近编辑人',
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最近编辑时间',
PRIMARY KEY(id),
KEY ix_tm_analysis_parameter_mode(mode,updated_at,id),
CONSTRAINT fk_tm_analysis_parameter_image FOREIGN KEY(image_id) REFERENCES tm_analysis_parameter_image(id),
CONSTRAINT fk_tm_analysis_parameter_creator FOREIGN KEY(created_by) REFERENCES sys_user(user_id),
CONSTRAINT fk_tm_analysis_parameter_editor FOREIGN KEY(updated_by) REFERENCES sys_user(user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin COMMENT='独立共享分析参数资料,仅存储不参与测试计算';
-- 已有轮次保持 NULL;逐列检查使重复执行及新版001后的执行都不会重置快照。
SET @tm_analysis_schema=DATABASE();
SET @tm_analysis_ddl=IF(
EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@tm_analysis_schema AND TABLE_NAME='tm_test_run' AND COLUMN_NAME='analysis_parameters_json'),
'SELECT 1',
'ALTER TABLE tm_test_run ADD COLUMN analysis_parameters_json LONGTEXT NULL COMMENT ''创建轮次时选用的共享分析参数快照,不回写资料后续编辑'''
);
PREPARE testing_analysis_upgrade FROM @tm_analysis_ddl;
EXECUTE testing_analysis_upgrade;
DEALLOCATE PREPARE testing_analysis_upgrade;
-- 只向已有测试读取角色补充新页面,不给普通用户添加测试资格或写权限。
SET @tm_analysis_parent=(SELECT menu_id FROM sys_menu WHERE parent_id=0 AND path='testing' LIMIT 1);
INSERT INTO sys_menu(menu_name,parent_id,order_num,path,component,route_name,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time)
SELECT '分析参数',@tm_analysis_parent,6,'analysis-parameters','testing/analysisParameters/index','TestingAnalysisParameters',1,1,'C','0','0','testing:read','chart','admin',CURRENT_TIMESTAMP
WHERE @tm_analysis_parent IS NOT NULL AND NOT EXISTS(SELECT 1 FROM sys_menu WHERE parent_id=@tm_analysis_parent AND path='analysis-parameters');
INSERT INTO sys_role_menu(role_id,menu_id)
SELECT DISTINCT source.role_id,target.menu_id FROM sys_role_menu source
JOIN sys_menu readable ON readable.menu_id=source.menu_id
JOIN sys_role role_record ON role_record.role_id=source.role_id
JOIN sys_menu target ON target.parent_id=@tm_analysis_parent AND target.path='analysis-parameters'
WHERE readable.parent_id=@tm_analysis_parent AND readable.perms='testing:read'
AND role_record.del_flag='0' AND NOT EXISTS(SELECT 1 FROM sys_role_menu existing WHERE existing.role_id=source.role_id AND existing.menu_id=target.menu_id);

View File

@ -0,0 +1,58 @@
package com.ruoyi.testing.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.testing.service.TestingAnalysisParameterService;
import com.ruoyi.testing.storage.TestingImageStorage;
import static com.ruoyi.testing.support.TestingJson.bad;
import java.nio.charset.StandardCharsets;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/** 共享分析参数入口独立于项目和标定,所有动作由服务层叠加全局测试权限。 */
@RestController
@RequestMapping("/testing")
public class TestingAnalysisParameterController {
private final TestingAnalysisParameterService service;
/** 控制器不接收存储地址、用户身份或项目归属,只转交白名单资料请求。 */
public TestingAnalysisParameterController(TestingAnalysisParameterService service) {this.service=service;}
/** 服务器分页、模式及名称筛选,避免共享资料库被一次性全量下载。 */
@GetMapping("/analysis-parameters")
public AjaxResult list(@RequestParam(defaultValue="") String mode,@RequestParam(defaultValue="") String keyword,
@RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="20") int pageSize) {return AjaxResult.success(service.list(mode,keyword,page,pageSize));}
/** 详情始终重新检查全局测试读取资格。 */
@GetMapping("/analysis-parameters/{id}") public AjaxResult get(@PathVariable long id) {return AjaxResult.success(service.get(id));}
/** 新建记录只接受表单数据,版本和创建用户由服务器生成。 */
@PostMapping("/analysis-parameters") public AjaxResult create(@RequestBody JsonNode body) {return AjaxResult.success(service.save(null,body));}
/** 修改时必须携带所见版本,冲突不会覆盖共享资料。 */
@PutMapping("/analysis-parameters/{id}") public AjaxResult update(@PathVariable long id,@RequestBody JsonNode body) {return AjaxResult.success(service.save(id,body));}
/** 文件先限制传输大小,再交由服务检查真实类型、像素及私有存储事务。 */
@PostMapping("/analysis-parameter-images")
public AjaxResult upload(@RequestParam String mode,@RequestParam("file") MultipartFile file) throws java.io.IOException {
if(file.getSize()>TestingImageStorage.MAX_BYTES) throw bad("截图不能超过 50MB");
return AjaxResult.success(service.upload(mode,file.getOriginalFilename(),file.getBytes()));
}
/** 原图元数据用于展示和模式复核,不返回私有 MinIO 对象地址。 */
@GetMapping("/analysis-parameter-images/{id}/info") public AjaxResult info(@PathVariable long id) {return AjaxResult.success(service.info(id));}
/** 图片经鉴权 Blob 返回且禁止缓存,退出登录后不能继续用固定地址访问。 */
@GetMapping("/analysis-parameter-images/{id}")
public ResponseEntity<byte[]> image(@PathVariable long id) {
var image=service.image(id);
return ResponseEntity.ok().contentType(MediaType.parseMediaType(image.get("mediaType").toString()))
.header("X-Content-Type-Options","nosniff").header(HttpHeaders.CACHE_CONTROL,"no-store")
.header(HttpHeaders.CONTENT_DISPOSITION,ContentDisposition.inline().filename(image.get("name").toString(),StandardCharsets.UTF_8).build().toString())
.body((byte[])image.get("bytes"));
}
/** 只识别 URL 中的当前原图,不允许客户端提交另一个路径或自由提示词。 */
@PostMapping("/analysis-parameter-images/{id}/recognition") public AjaxResult recognize(@PathVariable long id) {return AjaxResult.success(service.recognize(id));}
}

View File

@ -0,0 +1,48 @@
package com.ruoyi.testing.mapper;
import java.util.*;
import org.apache.ibatis.annotations.*;
/** 独立资料库不拼接项目成员关系;服务层负责全局测试资格和固定模式校验。 */
@Mapper
public interface TestingAnalysisParameterMapper {
/** 筛选始终绑定参数并分页,避免共享资料增长后一次传输全部记录。 */
@Select("SELECT * FROM tm_analysis_parameter WHERE (#{mode}='' OR mode=#{mode}) AND (#{keyword}='' OR name LIKE CONCAT('%',#{keyword},'%')) ORDER BY updated_at DESC,id DESC LIMIT #{limit} OFFSET #{offset}")
List<Map<String,Object>> records(@Param("mode") String mode,@Param("keyword") String keyword,@Param("limit") int limit,@Param("offset") long offset);
/** 总数和列表使用相同条件,分页不会因模式筛选出现错误页数。 */
@Select("SELECT COUNT(*) FROM tm_analysis_parameter WHERE (#{mode}='' OR mode=#{mode}) AND (#{keyword}='' OR name LIKE CONCAT('%',#{keyword},'%'))")
long count(@Param("mode") String mode,@Param("keyword") String keyword);
/** 普通详情不持锁;私有对象地址不在此表,公开字段仍由服务显式构造。 */
@Select("SELECT * FROM tm_analysis_parameter WHERE id=#{id}")
@Options(useCache=false) Map<String,Object> record(long id);
/** 当前读串行化资料编辑与轮次快照,禁止复用事务内旧查询缓存冒充当前版本。 */
@Select("SELECT * FROM tm_analysis_parameter WHERE id=#{id} FOR UPDATE")
@Options(useCache=false,flushCache=Options.FlushCachePolicy.TRUE) Map<String,Object> lockRecord(long id);
/** 一条资料只保存一种模式和当前截图,版本由数据库初始化而不采信客户端。 */
@Insert("INSERT INTO tm_analysis_parameter(name,mode,data_json,image_id,created_by,updated_by) VALUES(#{name},#{mode},#{data_json},#{image_id},#{created_by},#{updated_by})")
@Options(useGeneratedKeys=true,keyProperty="id") int insertRecord(Map<String,Object> row);
/** 更新必须匹配所见版本,不能用最后写入覆盖共享资料的并发编辑。 */
@Update("UPDATE tm_analysis_parameter SET name=#{name},mode=#{mode},data_json=#{data_json},image_id=#{image_id},updated_by=#{updated_by},updated_at=CURRENT_TIMESTAMP,version=version+1 WHERE id=#{id} AND version=#{version}")
int updateRecord(Map<String,Object> row);
/** 图片身份不可变;所有下载和识别先由服务检查当前资格。 */
@Select("SELECT * FROM tm_analysis_parameter_image WHERE id=#{id}")
@Options(useCache=false) Map<String,Object> image(long id);
/** 相同原图只在同一模式内去重,不能因为摘要相同就变换资料模式。 */
@Select("SELECT * FROM tm_analysis_parameter_image WHERE mode=#{mode} AND sha256=#{hash}")
Map<String,Object> duplicate(@Param("mode") String mode,@Param("hash") String hash);
/** 元数据和私有对象上传共用事务,主键仅由服务器生成。 */
@Insert("INSERT INTO tm_analysis_parameter_image(mode,name,media_type,object_key,sha256,size,width,height,created_by) VALUES(#{mode},#{name},#{media_type},#{object_key},#{sha256},#{size},#{width},#{height},#{created_by})")
@Options(useGeneratedKeys=true,keyProperty="id") int insertImage(Map<String,Object> image);
/** 缓存首个有效候选,既不覆盖人工资料,也不将失败或错图写成成功结果。 */
@Update("UPDATE tm_analysis_parameter_image SET recognition_json=#{data} WHERE id=#{id} AND recognition_json IS NULL")
int cacheRecognition(@Param("id") long id,@Param("data") String data);
}

View File

@ -0,0 +1,163 @@
package com.ruoyi.testing.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.testing.mapper.*;
import com.ruoyi.testing.recognition.TestingAnalysisParameterRecognition;
import com.ruoyi.testing.security.TestingAccess;
import com.ruoyi.testing.storage.TestingImageStorage;
import static com.ruoyi.testing.support.TestingJson.*;
import java.util.*;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.*;
import org.springframework.transaction.annotation.*;
import org.springframework.transaction.support.TransactionTemplate;
/** 共享分析参数只负责资料、证据和轮次快照,不参与测试指标或标定计算。 */
@Service
public class TestingAnalysisParameterService {
private final TestingAnalysisParameterMapper db;
private final TestingMapper audits;
private final TestingAccess access;
private final TestingImageStorage storage;
private final TestingAnalysisParameterData rules;
private final TestingAnalysisParameterRecognition recognition;
private final TransactionTemplate transaction;
/** 复用全局测试权限和私有存储,短事务仅在模型返回后核对资格及写缓存。 */
public TestingAnalysisParameterService(TestingAnalysisParameterMapper db,TestingMapper audits,TestingAccess access,TestingImageStorage storage,
TestingAnalysisParameterData rules,TestingAnalysisParameterRecognition recognition,PlatformTransactionManager manager) {
this.db=db; this.audits=audits; this.access=access; this.storage=storage; this.rules=rules; this.recognition=recognition;
transaction=new TransactionTemplate(manager);
}
/** 共享列表只检查全局读取资格;分页上限防止客户端要求无界扫描和传输。 */
public Map<String,Object> list(String mode,String keyword,int page,int size) {
access.permission("read"); String selected=mode==null || mode.isBlank()?"":rules.mode(mode);
String search=text(keyword,100,false,"名称搜索"); if(page<1 || size<1 || size>100) throw bad("分页参数无效");
List<Map<String,Object>> rows=new ArrayList<>();
for(var row:db.records(selected,search,size,((long)page-1)*size)) rows.add(publicRecord(row));
return map("items",rows,"total",db.count(selected,search),"page",page,"pageSize",size);
}
/** 每次查看都校验当前测试读取资格,不因曾经打开过页面而继续授权。 */
public Map<String,Object> get(long id) {access.permission("read"); return publicRecord(requireRecord(db.record(id)));}
/**
* 保存人工核对的资料;原图身份、模式和字符串格式在同一事务中复核。
* @param id 编辑对象的服务端主键,null 表示新增。
* @param body 仅允许名称、模式、参数、截图及乐观锁版本;不接受项目归属。
* @return 数据库中已保存的新版本完整记录;冲突或审计失败时整次修改回滚。
*/
@Transactional public Map<String,Object> save(Long id,JsonNode body) {
requireWrite(); rules.allowed(body,Set.of("name","mode","values","imageId","version"));
String mode=rules.mode(body.path("mode").asText()); String name=text(body.path("name").asText(),120,true,"记录名称");
ObjectNode values=rules.normalize(mode,body.path("values")); boolean present=false;
for(JsonNode value:values) if(!value.asText().isBlank()) present=true;
if(!present) throw bad("请至少录入一项分析参数");
long imageId=positive(body.path("imageId"),"截图"); Map<String,Object> image=db.image(imageId);
if(image==null || !mode.equals(image.get("mode"))) throw bad("截图与当前分析参数模式不一致");
Map<String,Object> before=id==null?null:requireRecord(db.lockRecord(id));
Long expected=body.path("version").isMissingNode() || body.path("version").isNull()?null:positive(body.path("version"),"版本");
if(before!=null) version(before,expected);
Map<String,Object> row=map("id",id,"name",name,"mode",mode,"data_json",write(values),"image_id",imageId,"version",expected,"created_by",access.actor(),"updated_by",access.actor());
if(before==null) db.insertRecord(row);
else if(db.updateRecord(row)!=1) throw badConflict();
long saved=id(row,"id"); Map<String,Object> result=publicRecord(requireRecord(db.record(saved)));
audit(before==null?"CREATE":"EDIT","ANALYSIS_PARAMETER",saved,before==null?null:publicRecord(before),result); return result;
}
/**
* 上传不可变原始截图,同模式相同摘要复用身份;并发首次上传由唯一索引收口。
* @param mode 表单所选模式,识别时仍独立核对图片实际模式。
* @param name 文件名仅显示,不构成存储路径。
* @param bytes 原图,格式、像素和摘要由服务器检测。
* @return 无私有对象键的元数据;失败回滚只补偿本次上传对象。
*/
@Transactional public Map<String,Object> upload(String mode,String name,byte[] bytes) {
requireWrite(); rules.mode(mode); String filename=text(name,255,true,"截图文件名");
var info=storage.inspect(bytes); var old=db.duplicate(mode,info.hash()); if(old!=null) return publicImage(old);
String key=storage.saveAnalysisParameters(bytes,info);
Map<String,Object> row=map("mode",mode,"name",filename,"media_type",info.mediaType(),"object_key",key,"sha256",info.hash(),
"size",bytes.length,"width",info.width(),"height",info.height(),"created_by",access.actor());
// 唯一索引冲突必须使本事务回滚,才能补偿本次对象;不在失败事务里继续复用对方记录。
try {db.insertImage(row);} catch(DuplicateKeyException e) {throw bad("该截图正在由另一请求保存,请稍后重试");}
audit("UPLOAD","ANALYSIS_PARAMETER_IMAGE",id(row,"id"),null,publicImage(row)); return publicImage(row);
}
/** 共享图片元数据通过全局测试读取权限访问,不暴露对象键及模型内部原文。 */
public Map<String,Object> info(long id) {return publicImage(authorizedImage(id,"read"));}
/** 读取原图前鉴权,并继续验证共享命名空间、长度和摘要,防止项目证据被替换进来。 */
public Map<String,Object> image(long id) {
var image=authorizedImage(id,"read"); return map("name",image.get("name"),"mediaType",image.get("media_type"),"bytes",storage.readAnalysisParameters(image));
}
/**
* 当前图的识别不持数据库锁,返回后短事务复核资格,候选从不自动写入资料。
* @param id 页面当前选中的图片 ID;模式和私有地址只能来自数据库。
* @return 当前图片身份及规范化候选,供前端核对仍为当前表单后显式填入。
*/
public Map<String,Object> recognize(long id) {
var image=authorizedImage(id,"write"); String mode=rules.mode(image.get("mode").toString()); byte[] bytes=storage.readAnalysisParameters(image);
JsonNode candidate=image.get("recognition_json")==null?recognition.recognize(mode,bytes,image.get("media_type").toString()):read(image.get("recognition_json"));
return transaction.execute(status->{
requireWrite(); db.cacheRecognition(id,write(candidate)); var current=db.image(id); JsonNode cached=read(current.get("recognition_json"));
if(!mode.equals(cached.path("mode").asText())) throw bad("识别缓存与当前分析参数模式不一致");
ObjectNode output=JSON.createObjectNode(); output.put("mode",mode); output.set("values",rules.normalize(mode,cached.path("values")));
output.putArray("warnings").add("请对照当前截图核对识别参数,未识别的数据保持空白。"); return map("imageId",id,"mode",mode,"data",output);
});
}
/**
* 轮次事务在项目锁后当前读资料,冻结使用者选择时的版本及原图引用。
* @param id 共享资料主键,不能通过提交整段客户端参数绕过版本检查。
* @param expected 使用者打开选择列表时的版本,变更后必须刷新重选。
* @return 脱离数据库行的只读快照;后续资料编辑不会回写它。
*/
@Transactional(propagation=Propagation.MANDATORY)
public Map<String,Object> snapshot(long id,Long expected) {
access.permission("read"); var row=requireRecord(db.lockRecord(id)); version(row,expected);
return map("id",row.get("id"),"name",row.get("name"),"mode",row.get("mode"),"version",row.get("version"),
"imageId",row.get("image_id"),"values",rules.normalize(row.get("mode").toString(),read(row.get("data_json"))));
}
/** 写入需要先有读取资格,不能只凭孤立的动作授权创建自己也不能核对的共享资料。 */
private void requireWrite() {access.permission("read"); access.permission("write");}
/** 图片没有项目归属,只按全局测试资格鉴权;写入口同样要求读取原图的资格。 */
private Map<String,Object> authorizedImage(long id,String action) {
if("write".equals(action)) requireWrite(); else access.permission("read");
var image=db.image(id); if(image==null) throw TestingAccess.denied(); return image;
}
/** 统一不存在响应,调用方不得以空值继续创建伪造快照或更新对象。 */
private Map<String,Object> requireRecord(Map<String,Object> row) {if(row==null) throw TestingAccess.denied(); return row;}
/** 主键和版本只接收可安全转换的正整数,禁止小数截断或超大数字回绕。 */
private long positive(JsonNode node,String label) {
if(!node.isIntegralNumber() || !node.canConvertToLong() || node.asLong()<1) throw bad(label+"应为有效正整数"); return node.asLong();
}
/** 显式返回固定字段,未来数据库增加内部信息时不会自动泄露给浏览器。 */
private Map<String,Object> publicRecord(Map<String,Object> row) {
return map("id",row.get("id"),"name",row.get("name"),"mode",row.get("mode"),"values",rules.normalize(row.get("mode").toString(),read(row.get("data_json"))),
"imageId",row.get("image_id"),"version",row.get("version"),"createdAt",row.get("created_at"),"updatedAt",row.get("updated_at"));
}
/** 原图元数据可用于核对来源,但私有键、识别缓存和上传者内部字段不外传。 */
private Map<String,Object> publicImage(Map<String,Object> row) {
return map("id",row.get("id"),"mode",row.get("mode"),"name",row.get("name"),"mediaType",row.get("media_type"),"sha256",row.get("sha256"),
"size",row.get("size"),"width",row.get("width"),"height",row.get("height"),"createdAt",row.get("created_at"));
}
/** 无项目的资料审计使用空项目键,保留创建/编辑前后值及操作者,不伪造项目关系。 */
private void audit(String action,String type,long id,Object before,Object after) {
audits.audit(map("project_id",null,"actor_id",access.actor(),"action",action,"target_type",type,"target_id",id,
"before_json",before==null?null:write(before),"after_json",write(after),"reason",""));
}
/** 与既有版本冲突保持同一状态码,客户端保留编辑内容并要求刷新后核对。 */
private com.ruoyi.common.exception.ServiceException badConflict() {return new com.ruoyi.common.exception.ServiceException("数据已更新,请刷新后重试",409);}
}

View File

@ -51,6 +51,11 @@ public class TestingImageStorage {
return saveObject(BusinessFileStorage.key("testing","projects/"+project+"/calibrations/robots/"+robot+"/"+UUID.randomUUID()+".bin"),bytes,info);
}
/** 共享分析参数不关联项目,使用独立私有目录,不能伪造项目或轮次主键复用旧路径。 */
public String saveAnalysisParameters(byte[] bytes,ImageInfo info) {
return saveObject(BusinessFileStorage.key("testing","analysis-parameters/"+UUID.randomUUID()+".bin"),bytes,info);
}
/** 统一私有上传和事务补偿,只有明确回滚的新对象可清理,历史截图不参与删除。 */
private String saveObject(String key,byte[] bytes,ImageInfo info) {
if(!storage.isEnabled()) throw bad("测试截图需要启用当前环境的 MinIO");
@ -75,6 +80,9 @@ public class TestingImageStorage {
return readObject(image,"testing/projects/"+id(image,"project_id")+"/calibrations/robots/"+id(image,"robot_id")+"/");
}
/** 全局测试读资格由服务检查,这里仍阻止把项目内私有证据当作共享图片读取。 */
public byte[] readAnalysisParameters(Map<String,Object> image) {return readObject(image,"testing/analysis-parameters/");}
/** 私有读取复核目录、长度和摘要,拒绝存储替换或客户端伪造引用。 */
private byte[] readObject(Map<String,Object> image,String prefix) {
String key=image.get("object_key").toString();

View File

@ -0,0 +1,41 @@
package com.ruoyi.testing;
import com.ruoyi.testing.mapper.TestingAnalysisParameterMapper;
import static com.ruoyi.testing.support.TestingJson.*;
import java.nio.file.*;
import java.util.*;
import java.util.regex.Pattern;
import org.h2.jdbcx.JdbcDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/** 隔离内存库执行真实新表 DDL 与 Mapper,不连接开发或生产数据库。 */
class TestingAnalysisParameterMapperTest {
/** 两张新表 DDL 可重入,模式去重、记录版本和分页筛选必须由真实 SQL 保证。 */
@Test void realSqlPreservesImageIdentityAndOptimisticVersions() throws Exception {
var source=new JdbcDataSource(); source.setURL("jdbc:h2:mem:analysis_"+UUID.randomUUID()+";MODE=MySQL;DATABASE_TO_LOWER=TRUE");
try(var connection=source.getConnection()) {
var statement=connection.createStatement(); statement.execute("CREATE TABLE sys_user(user_id BIGINT PRIMARY KEY)"); statement.execute("INSERT INTO sys_user VALUES(10)");
String script=Files.readString(Path.of("sql/005_analysis_parameters.sql"));
var tables=Pattern.compile("CREATE TABLE IF NOT EXISTS tm_analysis_parameter(?:_image)? \\(.*?\\) ENGINE=InnoDB[^;]*;",Pattern.DOTALL).matcher(script);
int count=0; while(tables.find()) {String ddl=tables.group().replaceAll("\\) ENGINE=InnoDB[^;]*;", ");"); statement.execute(ddl); statement.execute(ddl); count++;}
assertEquals(2,count);
var config=new Configuration(new Environment("test",new JdbcTransactionFactory(),source)); config.addMapper(TestingAnalysisParameterMapper.class);
try(var session=new SqlSessionFactoryBuilder().build(config).openSession(connection)) {
var db=session.getMapper(TestingAnalysisParameterMapper.class);
var image=map("mode","POSE","name","参数.png","media_type","image/png","object_key","testing/private","sha256","a".repeat(64),"size",30,"width",100,"height",100,"created_by",10L);
db.insertImage(image); long imageId=id(image,"id"); assertTrue(imageId>0); assertNotNull(db.duplicate("POSE","a".repeat(64))); assertNull(db.duplicate("TRAJECTORY","a".repeat(64)));
assertEquals(1,db.cacheRecognition(imageId,"{\"first\":true}")); assertEquals(0,db.cacheRecognition(imageId,"{}")); assertTrue(db.image(imageId).get("recognition_json").toString().contains("first"));
var row=map("name","位姿参数A","mode","POSE","data_json","{\"p1R\":\"-115.9060\"}","image_id",imageId,"created_by",10L,"updated_by",10L);
db.insertRecord(row); long recordId=id(row,"id"); assertEquals(1L,id(db.record(recordId),"version"));
row.put("version",1L); row.put("data_json","{\"p1R\":\"-99.00\"}"); assertEquals(1,db.updateRecord(row)); assertEquals(0,db.updateRecord(row));
assertEquals(2L,id(db.lockRecord(recordId),"version")); assertTrue(db.record(recordId).get("data_json").toString().contains("-99.00"));
assertEquals(1,db.count("POSE","参数")); assertEquals(0,db.count("TRAJECTORY","")); assertEquals(1,db.records("POSE","",20,0).size()); assertTrue(db.records("","",20,1).isEmpty());
row.put("image_id",999L); assertThrows(org.apache.ibatis.exceptions.PersistenceException.class,()->db.insertRecord(row));
}
}
}
}

View File

@ -0,0 +1,111 @@
package com.ruoyi.testing;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.testing.mapper.*;
import com.ruoyi.testing.recognition.TestingAnalysisParameterRecognition;
import com.ruoyi.testing.security.TestingAccess;
import com.ruoyi.testing.service.*;
import com.ruoyi.testing.storage.TestingImageStorage;
import static com.ruoyi.testing.support.TestingJson.*;
import java.util.Map;
import org.junit.jupiter.api.*;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.SimpleTransactionStatus;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
/** 共享库不能沿用项目归属判断,但全局只读和写资格始终在服务器检查。 */
class TestingAnalysisParameterServiceTest {
private final TestingAnalysisParameterMapper db=mock(TestingAnalysisParameterMapper.class);
private final TestingMapper audit=mock(TestingMapper.class);
private final TestingAccess access=mock(TestingAccess.class);
private final TestingImageStorage storage=mock(TestingImageStorage.class);
private final TestingAnalysisParameterRecognition recognition=mock(TestingAnalysisParameterRecognition.class);
private final PlatformTransactionManager manager=mock(PlatformTransactionManager.class);
private TestingAnalysisParameterService service;
/** 只替换数据库、私有对象及模型边界,参数规范化和服务状态转换使用真实实现。 */
@BeforeEach void setup() {
when(access.actor()).thenReturn(10L); when(manager.getTransaction(any())).thenReturn(new SimpleTransactionStatus());
service=new TestingAnalysisParameterService(db,audit,access,storage,new TestingAnalysisParameterData(),recognition,manager);
}
/** 共享图片没有项目或机器人字段,避免测试替身暗中依赖旧域身份。 */
private Map<String,Object> image(long id) {
return map("id",id,"mode","POSE","name","参数.png","media_type","image/png","object_key","private-key","sha256","hash","size",3L,"width",100,"height",100,"recognition_json",null);
}
/** 可变数据库行只作外部依赖替身,返回的快照必须与它脱离引用。 */
private Map<String,Object> record() {
return map("id",5L,"name","位姿参数","mode","POSE","image_id",77L,"version",3L,"data_json","{\"p1R\":\"-115.9060\"}");
}
/** 有测试读取资格即可查看共享资料,不要求调用者加入某个项目。 */
@Test void sharedReaderDoesNotNeedProjectMembership() {
when(db.record(5)).thenReturn(record()); var result=service.get(5);
assertEquals("-115.9060",((JsonNode)result.get("values")).path("p1R").asText());
verify(access).permission("read"); verify(access,never()).project(anyLong(),anyString(),anyBoolean());
}
/** 只读用户不能用上传、识别或保存接口旁路全局动作权限。 */
@Test void readOnlyWriterIsRejectedBeforePersistenceAndStorage() {
doThrow(TestingAccess.denied()).when(access).permission("write");
assertThrows(ServiceException.class,()->service.save(null,read("{}")));
assertThrows(ServiceException.class,()->service.upload("POSE","图.png",new byte[]{1}));
when(db.image(77)).thenReturn(image(77)); assertThrows(ServiceException.class,()->service.recognize(77));
verifyNoInteractions(storage,recognition); verify(db,never()).insertRecord(any());
}
/** 跨模式图引用和全空数据不能成为新记录,数字与原图必须属于同一种表单结构。 */
@Test void saveRejectsWrongImageModeAndEmptyParameters() {
var row=image(77); row.put("mode","TRAJECTORY"); when(db.image(77)).thenReturn(row);
assertThrows(ServiceException.class,()->service.save(null,read("{\"name\":\"参数\",\"mode\":\"POSE\",\"imageId\":77,\"values\":{\"p1X\":\"100\"}}")));
row.put("mode","POSE");
assertThrows(ServiceException.class,()->service.save(null,read("{\"name\":\"参数\",\"mode\":\"POSE\",\"imageId\":77,\"values\":{}}")));
verify(db,never()).insertRecord(any());
}
/** 过期表单不能覆盖别人保存的共享版本,失败后不写记录或审计。 */
@Test void optimisticConflictDoesNotOverwriteSharedRecord() {
when(db.lockRecord(5)).thenReturn(record()); when(db.image(77)).thenReturn(image(77));
var error=assertThrows(ServiceException.class,()->service.save(5L,read("{\"name\":\"参数\",\"mode\":\"POSE\",\"imageId\":77,\"version\":2,\"values\":{\"p1X\":\"100\"}}")));
assertEquals(409,error.getCode()); verify(db,never()).updateRecord(any()); verifyNoInteractions(audit);
}
/** 重复原图按模式和摘要复用,不生成额外私有对象且不泄露对象键。 */
@Test void duplicateUploadReusesImageAndHidesPrivateFields() {
when(storage.inspect(any())).thenReturn(new TestingImageStorage.ImageInfo("image/png",100,100,"hash"));
when(db.duplicate("POSE","hash")).thenReturn(image(77)); var result=service.upload("POSE","新文件名.png",new byte[]{1,2,3});
assertEquals(77L,result.get("id")); assertFalse(result.containsKey("object_key")); assertFalse(result.containsKey("recognition_json"));
verify(storage,never()).saveAnalysisParameters(any(),any());
}
/** 识别以当前图 ID 读取证据,模型返回后必须重新检查写资格才能缓存候选。 */
@Test void selectedImageIsRecognizedAndReturnedWithItsIdentity() {
var row=image(77); when(db.image(77)).thenReturn(row); byte[] bytes={4,5,6}; when(storage.readAnalysisParameters(row)).thenReturn(bytes);
when(recognition.recognize("POSE",bytes,"image/png")).thenReturn(read("{\"mode\":\"POSE\",\"values\":{\"p1X\":\"100\"},\"warnings\":[]}"));
when(db.cacheRecognition(eq(77L),anyString())).thenAnswer(call->{row.put("recognition_json",call.getArgument(1));return 1;});
var result=service.recognize(77); assertEquals(77L,result.get("imageId")); assertEquals("POSE",result.get("mode"));
assertEquals("100",((JsonNode)result.get("data")).at("/values/p1X").asText()); verify(access,times(2)).permission("write");
verify(manager).commit(any());
}
/** 等待模型期间失去写资格时,不能继续向共享库缓存或向表单返回候选。 */
@Test void revokedPermissionAfterModelPreventsCandidateReturn() {
var row=image(77); when(db.image(77)).thenReturn(row); when(storage.readAnalysisParameters(row)).thenReturn(new byte[]{1});
when(recognition.recognize(eq("POSE"),any(),eq("image/png"))).thenAnswer(call->{
doThrow(TestingAccess.denied()).when(access).permission("write"); return read("{\"mode\":\"POSE\",\"values\":{\"p1X\":\"100\"}}");
});
assertThrows(ServiceException.class,()->service.recognize(77)); verify(db,never()).cacheRecognition(anyLong(),anyString()); verify(manager).rollback(any());
}
/** 轮次快照保留所选版本的值,资料库后续更改不会修改已经返回的独立对象。 */
@Test void snapshotCopiesSelectedVersionAndRejectsChangedVersion() {
var row=record(); when(db.lockRecord(5)).thenReturn(row); var snapshot=service.snapshot(5,3L);
row.put("data_json","{\"p1R\":\"99\"}");
assertEquals("-115.9060",((JsonNode)snapshot.get("values")).path("p1R").asText()); assertEquals(77L,snapshot.get("imageId"));
assertThrows(ServiceException.class,()->service.snapshot(5,2L));
}
}

View File

@ -43,4 +43,16 @@ class TestingCalibrationStorageTest {
row.put("object_key","testing/projects/7/calibrations/robots/9/a.bin"); when(backend.read(anyString(),isNull(),anyInt())).thenReturn(new byte[]{3,2,1});
assertThrows(ServiceException.class,()->storage.readCalibration(row));
}
/** 共享参数有独立命名空间,不能把项目证据伪装成全局可读图片;回滚仍只补偿新对象。 */
@Test void sharedAnalysisImagesRejectProjectNamespaceAndRetainIntegrityChecks() throws Exception {
byte[] bytes={1,2,3}; String hash=HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
var info=new TestingImageStorage.ImageInfo("image/png",100,100,hash); String key=storage.saveAnalysisParameters(bytes,info);
assertTrue(key.startsWith("testing/analysis-parameters/"));
var row=map("object_key",key,"size",3L,"sha256",hash); when(backend.read(anyString(),isNull(),anyInt())).thenReturn(bytes);
assertArrayEquals(bytes,storage.readAnalysisParameters(row));
row.put("object_key","testing/projects/7/runs/9/a.bin"); assertThrows(ServiceException.class,()->storage.readAnalysisParameters(row));
TransactionSynchronizationManager.getSynchronizations().get(0).afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
verify(backend).discardFailedUpload(key,null);
}
}