Przeglądaj źródła

fix(cockpit): 按事务最终结果回收视频资源

Kazerin 3 tygodni temu
rodzic
commit
4d0e5d9c18

+ 14 - 8
docs/video-session-compatibility-20261110.md

@@ -22,29 +22,35 @@
 - 匿名 `heartbeat(id, token)`、`stop(id, token)`、`control(id, token, input)` 校验独立资源归属;凭据不能跨会话使用。原始凭据由 SecureRandom 生成 256 位,不进入数据库/日志;仅存 SHA-256 Base64URL 摘要并常量时间比较。
 - 沿用同一张会话表、同一设备行锁、全部 ACTIVE LIVE 的共享计数及 PLAYBACK 占用。不按匿名/用户来源分割计数,不对其它观看者做通道 stop。
 - `requireAnonymousSession(id, token, videoId, mode)` 提供设备/模式/归属/120秒观看有效性的统一校验,不代替能力校验或云台互斥。匿名已停止/超时心跳和控制明确失败,正确归属的 stop 仍可幂等清理;旧接口的已停止心跳保留成功无操作语义。
-- 心跳与释放共用既有设备行锁,并在锁后重新读取;锁查询清除 MyBatis 会话级旧快照,过期回收在锁后重新核对 last_seen。会话登记失败先按锁内预先取得的共享计数补偿媒体,不在已中止的数据库事务中再查计数;清理失败明确告知未确认,不假报成功。
+- 心跳与释放共用既有设备行锁,并在锁后重新读取;锁查询清除 MyBatis 会话级旧快照,过期回收在锁后重新核对 last_seen。Spring 管理入口在媒体调用前登记事务完成回调,最终回滚/提交异常后用 REQUIRES_NEW 重取锁、已提交会话及当前共享计数,避免原事务中止后用旧计数误停新观看者;提交结果不明但会话实际存在时保留给既有回收器。无 Spring 事务的构造调用仅供离线接缝测试,不作为生产并发保证。
+- 国标实时启动响应丢失可按已知设备/通道尝试补偿;没有取得回放 stream 或手动 proxyKey 时明确未确认并保留脱敏告警,不猜清理键、不声称自动回收成功。完整迟到/未知启动取消属于03的强化生命周期(见下文)。
 - 凭据是持有者能力,不是实名;不证明媒体地址受保护,不替代后续内网访问边界、能力/设备映射或物理云台停止验收。
 
 ## 离线验证记录
 
 - 基线离线 reactor `test-compile` 成功;核心新增接缝经历缺方法/行为失败 RED → 最小实现 GREEN,包含心跳/停止交错、过期扫描旧快照及事务中止后的媒体补偿反例。
-- 视频专项目前 **55 项通过,0 失败、0 错误、0 跳过**:[旧 HTTP/安全权限合同](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java>) 36 项,[匿名/旧用户与共享资源接缝](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java>) 19 项。
+- 视频专项目前 **60 项通过,0 失败、0 错误、0 跳过**:[旧 HTTP/安全权限合同](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/video/VideoDeviceCompatibilityTest.java>) 36 项,[匿名/旧用户与共享资源接缝](<../pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java>) 24 项;新增外层回滚、提交失败、成功提交、回滚后新观看者及实时启动响应丢失。事务测试由真实 Spring TransactionTemplate/同步回调驱动,数据库提交/回滚为边界替身。
 - 旧 HTTP 测试使用真实 SecurityConfig、JWT 过滤、TokenService、方法权限、Controller 和 VideoDeviceService,无真实应用服务启动;Redis/DB/媒体为外部替身。共享计数用数据库返回字面夹具(3→2→1),没有重写业务计数算法,但也不证明真实 SQL/锁执行。
-- 完整管网 reactor 回归已执行;默认失败即停在 zksy-system。为收齐其余结果,又用 `-Dmaven.test.failure.ignore=true` 继续收集,**该次退出0不代表全绿**:zksy-system 256 项中 2 失败、1 错误;zksy-admin 735 项中 17 失败。失败涉及报警生命周期/过滤权限与驾驶舱事件/历史统计,非视频用例;这些测试及报警实现未被本票修改,未另执行原始基点以作严格归因。保留原结果,不扩本票修复范围。
+- 完整管网 reactor 回归已执行;默认失败即停在 zksy-system。为收齐其余结果,又用 `-Dmaven.test.failure.ignore=true` 继续收集,**该次退出0不代表全绿**:zksy-system 256 项中 2 失败、1 错误;zksy-admin 746 项中 17 失败。失败涉及报警生命周期/过滤权限与驾驶舱事件/历史统计,非视频用例;这些测试及报警实现未被本票修改,未另执行原始基点以作严格归因。保留原结果,不扩本票修复范围。
 - 数据库替身不等于 Kingbase 的真实 SQL、行锁、事务或迁移验证;媒体替身不等于真实播放或设备停止。脚本未执行,后续现场验收仍需迁移/旧新会话并存实证。
-- 双轴代码审查以用户确认的 `4c4bc50a8e6b73eb83ecfe61cffaba3c5a988a61` 为基点,仅审本票独立提交 `32b2cf4a`。
+- 双轴代码审查以用户确认的 `4c4bc50a8e6b73eb83ecfe61cffaba3c5a988a61` 为基点;首轮审查独立提交 `32b2cf4a`,修复后再核对01与02/03/05的实际切片边界。
 
-## 审查进度(票据仍打开)
+## 审查修复与切片边界
 
 ### Standards
 
-硬违规0;两项判断性重复代码建议:匿名锁后归属校验序列可收拢;两份测试的数据库行快照替身可以统一。没有规范轴阻断项;为保持本票小范围,夹具提取不是验收前置。
+首轮硬违规0、判断性重复代码建议2。已收拢匿名锁后归属校验;两份测试的数据库行快照替身暂保留在各自HTTP/服务接缝内,避免额外测试基础设施;该建议不是验收前置。
 
 ### Spec
 
-必要修复2项:① insert成功不等于事务提交,提交失败/外层回滚/启动结果未确认尚未有完整补偿,须围绕最终事务结果和资源身份处理;②空或缺少必要播放/清理字段的媒体Map可能登记成ACTIVE。第二项已补公开接缝反例与模式字段校验,55项专项复验通过;第一项仍在实施,不因已有专项绿灯而关闭本票。
+首轮指出媒体响应假成功与事务补偿缺口。空/缺必要字段/非法媒体地址或stream已用公开接缝反例修复;最终事务回滚/提交失败已补新事务内锁后复查和补偿,不把insert=1当提交成功。复查七票切片后,复杂取消、迟到和未知启动的强化补偿明确已分配在[03票:19–23](<E:/City-Lifeline-Cockpit-TvT/.scratch/cockpit-video-monitoring/issues/03-三入口统一与观看资源生命周期.md#L19-L23>),本票不提前改造整套媒体信令层,也不以01完成替代03验收。
 
-另需核实SQL中止后的锁生命周期:失败后的补偿不能只依赖原事务预取计数,须防止误停异常后加入的其它观看者。当前迁移与提交只是实施阶段产物,不是可发布或真实资源回收验收结论。
+### 交接给02/03/05/07的已知边界
+
+- [02票:21–23](<E:/City-Lifeline-Cockpit-TvT/.scratch/cockpit-video-monitoring/issues/02-最新指标入口打开匿名实时视频.md#L21-L23>)仍须验证首链基本失败退出;[05票:23](<E:/City-Lifeline-Cockpit-TvT/.scratch/cockpit-video-monitoring/issues/05-已有历史录像查询与可控回放.md#L23>)明确沿03处理迟到与登记失败。本票只交付兼容接缝,不发布匿名HTTP或播放器。
+- 回放stream由设备/通道/起止时间确定,不是唯一请求代次;手动proxyKey可能被ZLM响应覆盖。未知/迟到结果不能通过猜ID、同通道盲停来处理。03需核实/补齐精确取消及迟到防护,再由05消费。
+- 底层已有“尚未收流”超时关闭,但媒体到达会取消该定时器;成功响应丢失不能据此宣称有界回收。现有video-service stop的ready阶段、BYE失败及arrival订阅仍需03/07按实际资源路径验证。本轮未修改底层信令实现、未操作真实设备,不把HTTP200当资源已释放。
+- 真实迁移、SQL行锁、媒体播放、内部网络边界与物理停止仍须后续按既定票序验收;本票代码/离线替身不是可发布或现场验收结论。
 - 按用户本次明确授权,仅执行离线 Java 编译/测试;因项目规则,跳过应用 build/debug、浏览器调试、服务启停、真实迁移和设备操作。
 
 复现命令(仓库根目录,均不启动服务;源码工具保留 mtime 时需先刷新本票改动文件的 mtime,避免旧 compiler 增量缓存漏编):

+ 71 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/VideoSessionCompatibilityTest.java

@@ -261,6 +261,77 @@ class VideoSessionCompatibilityTest {
         verify(sessions, never()).insert(any(VideoSession.class));
     }
 
+    @Test void outerTransactionRollbackReleasesTheMediaStartedByAnUncommittedSession() {
+        BoundaryTransactions transactions = new BoundaryTransactions(() -> rows.clear());
+        withTransactions(transactions, template -> template.execute(status -> {
+            service.startAnonymous(DEVICE, null);
+            status.setRollbackOnly();
+            return null;
+        }));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void aLostLiveStartResponseStillUsesTheKnownResourceForRollbackCleanup() {
+        when(media.get(eq(LIVE_START), anyMap())).thenThrow(new ServiceException("启动响应超时"));
+        withTransactions(new BoundaryTransactions(() -> rows.clear()), template ->
+                assertThrows(ServiceException.class, () -> template.execute(status -> service.startAnonymous(DEVICE, null))));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void failedCommitIsNotConfusedWithSuccessfulSessionRegistration() {
+        BoundaryTransactions transactions = new BoundaryTransactions(() -> rows.clear());
+        transactions.failNextCommit = true;
+        withTransactions(transactions, template -> assertThrows(org.springframework.transaction.TransactionSystemException.class,
+                () -> template.execute(status -> service.startAnonymous(DEVICE, null))));
+        verify(media).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void rollbackCleanupPreservesAViewerThatJoinedAfterTheFailedTransaction() {
+        BoundaryTransactions transactions = new BoundaryTransactions(() -> {
+            rows.clear();
+            when(sessions.selectCount(any())).thenReturn(1L); // a new committed viewer after rollback
+        });
+        withTransactions(transactions, template -> template.execute(status -> {
+            service.startAnonymous(DEVICE, null);
+            status.setRollbackOnly();
+            return null;
+        }));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    @Test void successfulCommitDoesNotRunFailureCleanup() {
+        withTransactions(new BoundaryTransactions(() -> rows.clear()), template ->
+                template.execute(status -> service.startAnonymous(DEVICE, null)));
+        verify(media, never()).get(eq(LIVE_STOP), anyMap());
+    }
+
+    private void withTransactions(BoundaryTransactions transactions,
+                                  java.util.function.Consumer<org.springframework.transaction.support.TransactionTemplate> work) {
+        try (org.springframework.context.annotation.AnnotationConfigApplicationContext context =
+                     new org.springframework.context.annotation.AnnotationConfigApplicationContext()) {
+            context.registerBean(org.springframework.transaction.PlatformTransactionManager.class, () -> transactions);
+            context.refresh();
+            context.getAutowireCapableBeanFactory().autowireBean(service);
+            work.accept(new org.springframework.transaction.support.TransactionTemplate(transactions));
+        }
+    }
+
+    /** Database transaction boundary substitute; Spring drives real synchronization callbacks. */
+    private static final class BoundaryTransactions extends org.springframework.transaction.support.AbstractPlatformTransactionManager {
+        private final Runnable rollback;
+        private boolean failNextCommit;
+        private BoundaryTransactions(Runnable rollback) { this.rollback = rollback; setRollbackOnCommitFailure(true); }
+        @Override protected Object doGetTransaction() { return new Object(); }
+        @Override protected void doBegin(Object transaction, org.springframework.transaction.TransactionDefinition definition) { }
+        @Override protected void doCommit(org.springframework.transaction.support.DefaultTransactionStatus status) {
+            if (failNextCommit) {
+                failNextCommit = false;
+                throw new org.springframework.transaction.TransactionSystemException("database commit failed");
+            }
+        }
+        @Override protected void doRollback(org.springframework.transaction.support.DefaultTransactionStatus status) { rollback.run(); }
+    }
+
     private static VideoSession copy(VideoSession row) {
         if (row == null) return null;
         VideoSession copy = new VideoSession();

+ 81 - 30
pipe-network-service/zksy-system/src/main/java/com/zksy/base/video/VideoDeviceService.java

@@ -15,6 +15,11 @@ import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.scheduling.annotation.Scheduled;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronization;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
 import java.net.URI;
 import java.nio.charset.StandardCharsets;
 import java.security.MessageDigest;
@@ -43,6 +48,13 @@ public class VideoDeviceService {
     private final VideoSessionMapper sessions;
     private final EquipmentBaseService equipmentService;
     private final Clock clock;
+    private TransactionTemplate rollbackCleanup;
+
+    @org.springframework.beans.factory.annotation.Autowired(required=false)
+    void configureRollbackCleanup(PlatformTransactionManager manager) {
+        rollbackCleanup=new TransactionTemplate(manager);
+        rollbackCleanup.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
+    }
 
     @org.springframework.beans.factory.annotation.Autowired
     public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings) {
@@ -167,21 +179,11 @@ public class VideoDeviceService {
         String mode=range==null?"LIVE":"PLAYBACK";
         // Capture under the video lock, before an insert error can abort the DB transaction.
         long existingLive=range==null?activeLiveCount(id,null):0;
-        Object response;
         if(range!=null) {
             requireGb(row);
             validateRange(range);
             if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getMode,"PLAYBACK").eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("此通道已有录像回放,请结束后重试");
-            response=collector.get("/api/playback/start",rangeParams(row,range));
-        }
-        else if(GB28181.equals(row.getSourceType()))response=collector.get("/api/play/start/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of());
-        else {
-            validateManualUrl(row.getVideoUrl());
-            String scheme=URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT);
-            response=scheme.startsWith("rt")?collector.post("/internal/video/manual/start",Map.of("id",id,"url",row.getVideoUrl())):Map.of("url",row.getVideoUrl(),"native",true);
-        }
-        if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
-        Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
+        } else if(!GB28181.equals(row.getSourceType()))validateManualUrl(row.getVideoUrl());
         VideoSession session=new VideoSession();
         session.setSessionId(UUID.randomUUID().toString());
         session.setVideoId(id);
@@ -189,31 +191,79 @@ public class VideoDeviceService {
         session.setAnonymousTokenHash(anonymousTokenHash);
         session.setMode(mode);
         session.setStatus("ACTIVE");
-        session.setGbDeviceId(row.getGbDeviceId());
-        session.setGbChannelId(row.getGbChannelId());
-        session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
-        Object proxyKey=data.remove("proxyKey");
-        session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
+        session.setGbDeviceId(GB28181.equals(row.getSourceType())?row.getGbDeviceId():null);
+        session.setGbChannelId(GB28181.equals(row.getSourceType())?row.getGbChannelId():null);
         session.setCreateTime(LocalDateTime.now(clock));
         session.setLastSeen(session.getCreateTime());
+        boolean deferredCleanup=false;
+        boolean responseReceived=false;
+        boolean mediaAttempted=false;
+        boolean nativeStream=!GB28181.equals(row.getSourceType())&&!URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT).startsWith("rt");
         try {
+            deferredCleanup=cleanupOnRollback(session,nativeStream);
+            mediaAttempted=true;
+            Object response;
+            if(range!=null)response=collector.get("/api/playback/start",rangeParams(row,range));
+            else if(GB28181.equals(row.getSourceType()))response=collector.get("/api/play/start/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of());
+            else {
+                String scheme=URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT);
+                response=scheme.startsWith("rt")?collector.post("/internal/video/manual/start",Map.of("id",id,"url",row.getVideoUrl())):Map.of("url",row.getVideoUrl(),"native",true);
+            }
+            responseReceived=true;
+            if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
+            Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
+            session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
+            Object proxyKey=data.remove("proxyKey");
+            session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
             if(!List.of("url","flv","https_flv","ws_flv","wss_flv","hls","https_hls","webrtc").stream()
                     .map(data::get).anyMatch(VideoDeviceService::isPlayableAddress))throw new ServiceException("媒体服务没有返回有效播放地址");
             if(GB28181.equals(row.getSourceType())||!Boolean.TRUE.equals(data.get("native")))safeStream(session.getStreamId());
             if(!GB28181.equals(row.getSourceType())&&!Boolean.TRUE.equals(data.get("native"))&&session.getProxyKey()==null)
                 throw new ServiceException("媒体服务没有返回代理清理标识");
             if(sessions.insert(session)!=1)throw new ServiceException("播放会话登记失败");
+            data.put("sessionId",session.getSessionId());
+            data.put("mode",mode);
+            return data;
         } catch(RuntimeException registrationFailure) {
+            if(!mediaAttempted)throw registrationFailure;
+            if(deferredCleanup)throw new ServiceException("视频启动或会话登记失败,媒体清理结果未确认");
             try { stopMedia(session,existingLive); }
             catch(RuntimeException cleanupFailure) {
                 log.warn("视频会话登记失败且媒体清理未确认: {}",session.getSessionId());
                 throw new ServiceException("播放会话登记失败,媒体清理未确认,请联系管理员");
             }
-            throw new ServiceException("播放会话登记失败");
+            throw new ServiceException(responseReceived?"播放会话登记失败":"视频启动失败,媒体结果与清理未确认");
         }
-        data.put("sessionId",session.getSessionId());
-        data.put("mode",mode);
-        return data;
+    }
+
+    private boolean cleanupOnRollback(VideoSession session,boolean nativeStream) {
+        if(!TransactionSynchronizationManager.isActualTransactionActive())return false;
+        if(rollbackCleanup==null||!TransactionSynchronizationManager.isSynchronizationActive())
+            throw new ServiceException("视频事务清理未配置");
+        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
+            @Override public void afterCompletion(int status) {
+                if(status==STATUS_COMMITTED||nativeStream)return;
+                try {
+                    rollbackCleanup.execute(cleanupStatus -> {
+                        sessions.lockVideo(session.getVideoId());
+                        // A commit with an uncertain acknowledgement may have persisted the session.
+                        // Keep it for the ordinary heartbeat reaper, never stop a registered viewer.
+                        if(sessions.selectById(session.getSessionId())!=null)return null;
+                        if("PLAYBACK".equals(session.getMode())&&sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
+                                .eq(VideoSession::getVideoId,session.getVideoId()).eq(VideoSession::getMode,"PLAYBACK")
+                                .eq(VideoSession::getStatus,"ACTIVE"))>0)return null;
+                        long others=activeLiveCount(session.getVideoId(),null);
+                        if(others==0&&session.getGbDeviceId()==null&&session.getProxyKey()==null)
+                            throw new ServiceException("未取得代理清理标识,媒体资源需人工核查");
+                        stopMedia(session,others);
+                        return null;
+                    });
+                } catch(RuntimeException cleanupFailure) {
+                    log.warn("视频事务结束后媒体清理未确认,需人工核查: {}",session.getSessionId());
+                }
+            }
+        });
+        return true;
     }
 
     public Object records(String id,VideoRequests.Range range) {
@@ -253,7 +303,7 @@ public class VideoDeviceService {
         if(!(value instanceof String))return false;
         try {
             URI uri=URI.create((String)value);
-            return uri.getHost()!=null&&Set.of("http","https","ws","wss").contains(uri.getScheme());
+            return uri.getHost()!=null&&uri.getScheme()!=null&&Set.of("http","https","ws","wss").contains(uri.getScheme().toLowerCase(Locale.ROOT));
         } catch(IllegalArgumentException invalid) { return false; }
     }
 
@@ -264,12 +314,17 @@ public class VideoDeviceService {
         } catch(NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); }
     }
 
+    private VideoSession activeAnonymousLocked(String id,String token) {
+        VideoSession session=ownedAnonymous(id,token);
+        sessions.lockVideo(session.getVideoId());
+        session=ownedAnonymous(id,token);
+        requireActiveAnonymous(session);
+        return session;
+    }
+
     @Transactional
     public void heartbeat(String id,String token) {
-        VideoSession s=ownedAnonymous(id,token);
-        sessions.lockVideo(s.getVideoId());
-        s=ownedAnonymous(id,token);
-        requireActiveAnonymous(s);
+        VideoSession s=activeAnonymousLocked(id,token);
         s.setLastSeen(LocalDateTime.now(clock));
         sessions.updateById(s);
     }
@@ -331,11 +386,7 @@ public class VideoDeviceService {
 
     @Transactional
     public void control(String id,String token,VideoRequests.Control input) {
-        VideoSession s=ownedAnonymous(id,token);
-        sessions.lockVideo(s.getVideoId());
-        s=ownedAnonymous(id,token);
-        requireActiveAnonymous(s);
-        controlSession(s,input);
+        controlSession(activeAnonymousLocked(id,token),input);
     }
 
     public void control(String id,VideoRequests.Control input) {