Просмотр исходного кода

test(video): 锁定空闲流被回收后仍能重新点播的回归

新增三条用例覆盖本次修复:
- hit=0 且 ZLM 已无该流 -> 推进到 CLOSED 且通道可再次点播;
- hit=0 但查询不到节点 -> 保持 CLOSING(未知不等于已停);
- 普通 legacy OPEN 对流已消失的情况可重新分配,而 live 流不产生多余 close。

同时把 getRtpInfo 替身改成如实反映 ZLM 的 rtp server 清单,避免用固定
exist=false 掩盖"流是否还在"这一关键事实。
Kazerin 3 недель назад
Родитель
Сommit
76b6127cfe

+ 5 - 1
video-service/src/test/java/com/zksy/video/lifecycle/ManagedGbDeepSeamTest.java

@@ -325,7 +325,11 @@ class ManagedGbDeepSeamTest {
             wire(zlmNode, "zlmServerFactory", zlmFactory); wire(zlmNode, "zlmresTfulUtils", zlm); wire(zlmNode, "userSetting", settings);
             wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode)); wire(media, "redisTemplate", redis);
             wire(media, "userSetting", settings); wire(media, "mediaServerMapper", mediaMapper); wire(media, "ssrcFactory", factory);
-            when(zlm.getRtpInfo(any(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":0,\"exist\":false}"));
+            when(zlm.getRtpInfo(any(), anyString())).thenAnswer(i -> {
+                JSONObject reply = new JSONObject(); reply.put("code", 0);
+                reply.put("exist", open.contains((String) i.getArgument(1)));
+                return reply;
+            });
             when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
                 String stream = (String) ((Map<?, ?>) i.getArgument(1)).get("stream_id");
                 openRequests.incrementAndGet(); open.add(stream); if (cancelDuringOpen) store.markStreamCancelled(stream);

+ 111 - 1
video-service/src/test/java/com/zksy/video/lifecycle/VideoStopReceiptRestartTest.java

@@ -1,5 +1,6 @@
 package com.zksy.video.lifecycle;
 
+import com.alibaba.fastjson2.JSONArray;
 import com.alibaba.fastjson2.JSONObject;
 import com.ruoyi.wvp.common.*;
 import com.ruoyi.wvp.common.InviteInfo;
@@ -209,6 +210,85 @@ class VideoStopReceiptRestartTest {
         assertTrue(new Instance(world).stopAdopted(handle));
     }
 
+/**
+     * ZLM reclaims an idle RTP server on its own ("流无人观看" -> on_stream_none_reader), so a later
+     * name-close legitimately answers code=0/hit=0. Treating that as "not stopped" strands the
+     * allocation in CLOSING forever and canReplaceAllocation() then rejects every future play on
+     * that channel. The allocation is finished only when ZLM positively reports the server absent.
+     */
+    @Test void hitZeroWithPositiveAbsenceEvidenceFinishesTheAllocation() throws Exception {
+        External world = new External();
+        world.closeReply = "{\"code\":0,\"hit\":0}";
+        Instance first = new Instance(world);
+        SSRCInfo info = first.open(LEGACY);
+        assertNotNull(info);
+        world.open.remove(LEGACY);   // ZLM reclaimed the idle server before we asked to close it
+        first.rtp.closeRTPServer(world.node, info);
+        VideoStopReceipts.Snapshot snapshot = first.receipts.read(world.node.getId(), LEGACY);
+        assertNotNull(snapshot);
+        assertEquals(VideoStopReceipts.RtpState.CLOSED, snapshot.allocation.state);
+        // The channel becomes playable again, which is the user-visible requirement.
+        assertNotNull(new Instance(world).open(LEGACY));
+    }
+
+    @Test void hitZeroWithoutAbsenceEvidenceStaysUnresolved() throws Exception {
+        External world = new External();
+        world.closeReply = "{\"code\":0,\"hit\":0}";
+        Instance first = new Instance(world);
+        SSRCInfo info = first.open(LEGACY);
+        assertNotNull(info);
+        first.rtp.closeRTPServer(world.node, info);
+        VideoStopReceipts.Snapshot snapshot = first.receipts.read(world.node.getId(), LEGACY);
+        assertNotNull(snapshot);
+        assertEquals(VideoStopReceipts.RtpState.CLOSING, snapshot.allocation.state);
+        assertNull(new Instance(world).open(LEGACY));
+    }
+
+    @Test void hitZeroWithUnreachableLookupStaysUnresolved() throws Exception {
+        External world = new External();
+        world.closeReply = "{\"code\":0,\"hit\":0}";
+        world.zlmLookupFails = true;
+        Instance first = new Instance(world);
+        SSRCInfo info = first.open(LEGACY);
+        assertNotNull(info);
+        first.rtp.closeRTPServer(world.node, info);
+        assertEquals(VideoStopReceipts.RtpState.CLOSING, first.receipts.read(world.node.getId(), LEGACY).allocation.state);
+        assertNull(new Instance(world).open(LEGACY));
+    }
+
+    /**
+     * A viewer that vanishes without a stop leaves the allocation OPEN while ZLM has already
+     * reclaimed the idle stream. The next play must retire that dead handle instead of failing
+     * on the header's close-receipt fence for ever.
+     */
+    @Test void staleOpenAllocationIsRetiredOnceZlmDroppedTheStream() throws Exception {
+        External world = new External();
+        Instance first = new Instance(world);
+        SSRCInfo stale = first.open(LEGACY);
+        assertNotNull(stale);
+        // Viewer never stops; ZLM reclaims the idle stream on its own.
+        world.open.remove(LEGACY);
+        SSRCInfo replacement = new Instance(world).open(LEGACY);
+        assertNotNull(replacement, "a dead handle must not block the channel for ever");
+        assertNotEquals(stale.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
+    }
+
+    /**
+     * The mirror case of the stale-handle fix: when ZLM still holds the stream, the retirement path
+     * must never fire reach into the receipt. A plain legacy OPEN is provenance rather than a lease
+     * (see canReplaceAllocation), so the channel legitimately accepts a fresh allocation.
+     */
+    @Test void liveStreamKeepsTheReceiptUntouched() throws Exception {
+        External world = new External();
+        Instance first = new Instance(world);
+        SSRCInfo original = first.open(LEGACY);
+        assertNotNull(original);
+        assertNotNull(new Instance(world).open(LEGACY));
+        // ZLM still holds it, so nothing was retired out from under the open stream.
+        assertTrue(world.open.contains(LEGACY));
+        assertTrue(world.closeRequests.isEmpty(), "no close may be dispatched for a live stream");
+    }
+
     @Test void hitZeroAndNonzeroCodeAreNotDurableCloseEvidence() throws Exception {
         for (String reply : List.of("{\"code\":0,\"hit\":0}", "{\"code\":-1,\"hit\":1}")) {
             External world = new External(); world.closeReply = reply;
@@ -310,6 +390,7 @@ class VideoStopReceiptRestartTest {
             wire(channelService, "deviceMapper", devices); wire(channelService, "channelMapper", channels);
             ZLMServerFactory zlm = new ZLMServerFactory(); wire(zlm, "zlmresTfulUtils", world.zlm);
             ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService(); wire(zlmNode, "zlmServerFactory", zlm);
+            wire(zlmNode, "zlmresTfulUtils", world.zlm);   // absence lookup goes through getRtpInfo too
             MediaServerServiceImpl media = new MediaServerServiceImpl(); wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode));
             wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class));
             wire(rtp, "ssrcFactory", ssrc); wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks);
@@ -370,6 +451,9 @@ class VideoStopReceiptRestartTest {
         final Map<Request, SipSubscribe.Event> inviteCallbacks = new IdentityHashMap<>();
         final AtomicInteger openRequests = new AtomicInteger(), calls = new AtomicInteger();
         boolean delayClose, throwDuringOpen;
+        /** Simulates an unreachable node, but only after the allocation already exists. */
+        boolean zlmLookupFails = false;
+        final AtomicInteger failLookupAfterOpen = new AtomicInteger();
         String closeReply = "{\"code\":0,\"hit\":1}";
         final FakeStringRedis ssrcRedis = new FakeStringRedis();
         External() throws Exception {
@@ -378,9 +462,35 @@ class VideoStopReceiptRestartTest {
             node.setId("node-a"); node.setType("zlm"); node.setRtpEnable(true); node.setSdpIp("127.0.0.1");
             device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP"); device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
             channel.setId(7); channel.setDeviceId("channel");
-            when(zlm.getRtpInfo(any(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":0,\"exist\":false}"));
+            // The open path relies on exist=false so a same-name allocation is created rather than
+            // reopened. Once an allocation is OPEN, an idle server may already have been reclaimed by
+            // ZLM, which is what the close path has to recognise, so report absence only once the
+            // stream is no longer in ZLM's inventory.
+            // Mirrors ZLM's real inventory. The open path only reads `code`/`exist`; the close and
+            // absence paths read the same answer, which is where an idle reclaim becomes visible.
+            when(zlm.getRtpInfo(any(), anyString())).thenAnswer(i -> {
+                String stream = i.getArgument(1);
+                if (zlmLookupFails && openRequests.get() > 0) throw new IllegalStateException("node unreachable");
+                boolean present = open.contains(stream);
+                JSONObject reply = new JSONObject();
+                reply.put("code", 0);
+                reply.put("exist", present);
+                // A live server keeps its bound port; 0 means "created but no stream yet".
+                if (present) reply.put("local_port", 30000);
+                return reply;
+            });
+            // Mirrors ZLM's real rtp-server inventory: a stream disappears from it once ZLM itself
+            // reclaims the idle server, which is exactly the case a hit=0 close has to recognise.
+            when(zlm.listRtpServer(any())).thenAnswer(i -> {
+                if (zlmLookupFails) throw new IllegalStateException("node unreachable");
+                JSONArray data = new JSONArray();
+                for (String stream : open) { JSONObject row = new JSONObject(); row.put("stream", stream); data.add(row); }
+                JSONObject reply = new JSONObject(); reply.put("code", 0); reply.put("data", data); reply.put("count", data.size());
+                return reply;
+            });
             when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
                 openRequests.incrementAndGet(); open.add((String) ((Map<?,?>) i.getArgument(1)).get("stream_id"));
+                if (zlmLookupFails) failLookupAfterOpen.incrementAndGet();
                 if (throwDuringOpen) throw new IllegalStateException("response lost after dispatch");
                 return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
             });