Ver código fonte

fix(video): 终止证据契约收紧且终态回执设置保留期

Kazerin 3 semanas atrás
pai
commit
a5a0a70737

+ 3 - 2
video-service/src/main/java/com/zksy/video/lifecycle/VideoLifecycleService.java

@@ -125,12 +125,13 @@ public class VideoLifecycleService {
             }
             // A transport flag can outlive its process. Only positive quiescence evidence from
             // the exact media adapter may settle it; an ordinary STOPPED/empty list cannot.
+            // Contract: a terminal status is claimed only together with allocationClosed, which
+            // every real adapter (GB/Manual) attaches exactly when it verified teardown.
             boolean quiescent = cleanup && TERMINAL.contains(state) && outcome != null
                     && Boolean.TRUE.equals(outcome.get("allocationClosed"));
             if (quiescent) row.setStartInFlight(false);
             if (row.isCancelled()) {
-                row.setStatus(cleanup && (quiescent || (!attempt.isStartInFlight() && !row.isStartInFlight()))
-                        && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
+                row.setStatus(quiescent && TERMINAL.contains(state) ? state : "CLEANUP_PENDING");
                 row.setMedia(null);
             } else if ("CLEANUP_PENDING".equals(state)) {
                 row.setStatus(state); row.setCancelled(true); row.setMedia(null);

+ 10 - 1
video-service/src/main/java/com/zksy/video/lifecycle/VideoStopReceipts.java

@@ -153,7 +153,11 @@ public class VideoStopReceipts {
                     validate(before, next, nodeId, stream);
                     String encoded = encode(next);
                     ops.multi(); transaction = true;
-                    ops.opsForValue().set(key, encoded);
+                    // Only a terminal receipt may expire: an unresolved allocation has to stay
+                    // readable after restart. Confirmed stops keep a bounded retention window
+                    // via a single SET ... EX inside this same transaction.
+                    if (retired(next)) ops.opsForValue().set(key, encoded, java.time.Duration.ofDays(7));
+                    else ops.opsForValue().set(key, encoded);
                     List<Object> committed = ops.exec(); transaction = false;
                     if (committed == null || committed.isEmpty()) return null;
                     for (Object result : committed) {
@@ -170,6 +174,11 @@ public class VideoStopReceipts {
         });
     }
 
+    /** A terminal allocation is retired: nothing can be reclaimed from it any more. */
+    private static boolean retired(Snapshot snapshot) {
+        return snapshot.allocation != null && snapshot.allocation.terminal();
+    }
+
     private void validate(Snapshot old, Snapshot next, String nodeId, String stream) {
         if (!Objects.equals(nodeId, next.nodeId) || !Objects.equals(stream, next.stream) || next.plays == null)
             throw new IllegalArgumentException("Receipt identity cannot change");

+ 4 - 2
video-service/src/test/java/com/zksy/video/lifecycle/VideoLifecycleRaceTest.java

@@ -65,7 +65,9 @@ class VideoLifecycleRaceTest {
     @Test void deletionAcknowledgedDuringAllocationIsNotPrematureStopEvidence() {
         VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
         when(media.supports("GB28181")).thenReturn(true);
-        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        // In-flight cleanup reports only a deletion ack; the completed allocation then attests teardown.
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"),
+                Map.of("status", "STOPPED", "allocationClosed", true));
         VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media));
         Map<String,Object> request = request();
         when(media.start(any())).thenAnswer(call -> {
@@ -102,7 +104,7 @@ class VideoLifecycleRaceTest {
         };
         VideoLifecycleMedia media = mock(VideoLifecycleMedia.class);
         when(media.supports("GB28181")).thenReturn(true);
-        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED", "allocationClosed", true));
         VideoLifecycleService service = new VideoLifecycleService(new Snapshots(), List.of(media), clock);
         Map<String,Object> request = new HashMap<>(request()); request.put("startDeadline", 31000L);
         when(media.start(any())).thenAnswer(call -> {

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

@@ -63,7 +63,7 @@ class VideoLifecycleServiceTest {
         when(media.start(any())).thenReturn(Map.of("status", "ACTIVE",
                 "media", Map.of("webrtc", "https://media.invalid/a"), "stream", "stream-x"));
         assertEquals("ACTIVE", service.start(body("gen-active")).get("status"));
-        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED"));
+        when(media.cancel(any())).thenReturn(Map.of("status", "STOPPED", "allocationClosed", true));
         assertEquals("STOPPED", service.cancel(body("gen-active")).get("status"));
         ArgumentCaptor<VideoLifecycleRecord> captured = ArgumentCaptor.forClass(VideoLifecycleRecord.class);
         verify(media).cancel(captured.capture());

+ 24 - 0
video-service/src/test/java/com/zksy/video/lifecycle/VideoStopReceiptRestartTest.java

@@ -129,6 +129,19 @@ class VideoStopReceiptRestartTest {
         assertEquals(2, world.closeRequests.size());
     }
 
+    @Test void terminalReceiptGetsABoundedRetentionWhileUnresolvedOnesDoNot() throws Exception {
+        External world = new External(); Instance instance = new Instance(world);
+        SSRCInfo allocation = instance.open(STREAM);
+        assertNotNull(allocation);
+        int before = world.redis.expirations.size();
+        assertTrue(instance.rtp.closeManagedRTPServer(world.node, allocation));
+        // A confirmed stop keeps a bounded retention window instead of living forever.
+        assertEquals(before + 1, world.redis.expirations.size(),
+                "a confirmed stop still needs a bounded retention window");
+        assertEquals(java.time.Duration.ofDays(7), world.redis.expirations.values().stream().reduce((a, b) -> b).orElse(null),
+                "a confirmed stop still needs a bounded retention window");
+    }
+
     @Test void definitiveInviteRefusalLetsARealRtpCloseConvergeWithoutADialog() throws Exception {
         External world = new External(); Instance instance = new Instance(world);
         SSRCInfo allocation = instance.play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { });
@@ -402,6 +415,7 @@ class VideoStopReceiptRestartTest {
         final StringRedisSerializer strings = new StringRedisSerializer();
         final AtomicInteger ssrc = new AtomicInteger(1), sequence = new AtomicInteger();
         Predicate<String> failWrite = value -> false;
+        final Map<String, java.time.Duration> expirations = new HashMap<>();
         Runnable beforeExec;
         @SuppressWarnings({"unchecked", "rawtypes"})
         RedisTemplate<Object,Object> client() {
@@ -418,6 +432,16 @@ class VideoStopReceiptRestartTest {
             doAnswer(i -> { watched.clear(); return null; }).when(redis).unwatch();
             when(vals.get(any())).thenAnswer(i -> serializer.deserialize(values.get(i.getArgument(0).toString())));
             when(vals.increment(any(), anyLong())).thenAnswer(i -> (long) sequence.incrementAndGet());
+            doAnswer(i -> {
+                String key = i.getArgument(0).toString(); Object value = i.getArgument(1); byte[] encoded = serializer.serialize(value);
+                java.time.Duration ttl = i.getArguments().length > 2 ? i.getArgument(2) : null;
+                Runnable write = () -> {
+                    if (failWrite.test(value.toString())) throw new IllegalStateException("Redis write unavailable");
+                    values.put(key, encoded); versions.merge(key, 1L, Long::sum);
+                    if (ttl != null) expirations.put(key, ttl);
+                };
+                if (multi[0]) queued.add(write); else write.run(); return null;
+            }).when(vals).set(any(), any(), any(java.time.Duration.class));
             doAnswer(i -> {
                 String key = i.getArgument(0).toString(); Object value = i.getArgument(1); byte[] encoded = serializer.serialize(value);
                 Runnable write = () -> {