فهرست منبع

fix(video): 记录INVITE终拒并支持离线后精确补发BYE

Kazerin 3 هفته پیش
والد
کامیت
1c0609b974

+ 11 - 5
video-service/src/main/java/com/ruoyi/wvp/gb28181/service/impl/PlayServiceImpl.java

@@ -420,7 +420,9 @@ public class PlayServiceImpl implements IPlayService {
             SsrcTransaction expected = receipt.dialog;
             boolean rtpClosed;
             try {
-                if (expected != null && !sessionManager.isSipTerminated(expected) && current != null) {
+                // The persisted original dialog still lets a restart/offline cleanup send the exact
+                // BYE after the live index was removed; a different replacement is rejected earlier.
+                if (expected != null && !sessionManager.isSipTerminated(expected)) {
                     // Only durable outgoing confirmation or a matched real peer BYE is protocol evidence.
                     cmder.streamByeCmd(device, channel.getDeviceId(), expected.getSipTransactionInfo(), event -> { });
                 }
@@ -434,7 +436,11 @@ public class PlayServiceImpl implements IPlayService {
                     rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, new SSRCInfo(0, null, "rtp", stream, stream));
                 if (retained.allocation != null) rtpClosed = receiveRtpServerService.closeManagedRTPServer(node, retained.allocation.info(stream));
             }
-            if (!rtpClosed || (receipt.inviteSent && (expected == null || !sessionManager.isSipTerminated(expected)))) return false;
+            // A definitive INVITE refusal establishes that no dialog exists for this attempt.
+            // Timeouts, lost replies, 401/407 and unknown states stay pending.
+            boolean refused = !receipt.inviteSent || expected != null && sessionManager.isInviteRejected(
+                    node.getId(), "rtp", stream, retained.allocation == null ? stream : retained.allocation.token);
+            if (!rtpClosed || (!refused && receipt.inviteSent && (expected == null || !sessionManager.isSipTerminated(expected)))) return false;
             SsrcTransaction now = sessionManager.getSsrcTransactionByStream("rtp", stream);
             if (now != null && !SipInviteSessionManager.sameDialog(expected, now)) return false;
             inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
@@ -554,8 +560,9 @@ public class PlayServiceImpl implements IPlayService {
                 receipt.cancelled = true; return snapshot;
             }) == null) return false;
             try {
-                if (current != null && !sessionManager.isSipTerminated(owned.dialog)) {
+                if (!sessionManager.isSipTerminated(owned.dialog)) {
                     // Explicit original dialog only; a peer termination is not an outgoing BYE confirmation.
+                    // It stays usable after offline removed the live session index.
                     cmder.streamByeCmd(device, owned.channelCode, owned.dialog.getSipTransactionInfo(), event -> { });
                 }
             } catch (InvalidArgumentException | SipException | ParseException | SsrcTransactionNotFoundException | RuntimeException ex) {
@@ -566,8 +573,7 @@ public class PlayServiceImpl implements IPlayService {
             invite = inviteStreamService.getInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
             if (!closed || !sessionManager.isSipTerminated(owned.dialog)
                     || (current != null && !SipInviteSessionManager.sameDialog(owned.dialog, current))
-                    || (invite != null && !adoptedInvite(owned, invite))) return false;
-            if (invite != null) inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
+                    || (invite != null && !adoptedInvite(owned, invite))) return false;            if (invite != null) inviteStreamService.removeInviteInfo(InviteSessionType.PLAY, channel.getId(), stream);
             return true;
         } catch (RuntimeException ex) {
             log.warn("[Adopted receipt] {}/{} remains pending: {}", node == null ? null : node.getId(), stream, ex.getMessage());

+ 43 - 1
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipInviteSessionManager.java

@@ -192,12 +192,18 @@ public class SipInviteSessionManager {
     }
 
     public PendingSipInvite matchPendingInvite(gov.nist.javax.sip.message.SIPResponse response) {
+        return matchPendingInvite(response, false);
+    }
+
+    /** Final refusals are not 2xx, so rejection attribution validates correlation headers only. */
+    private PendingSipInvite matchPendingInvite(gov.nist.javax.sip.message.SIPResponse response, boolean rejection) {
         String field = SipRequestBinding.key(response);
         if (field == null) return null;
         Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-request"), field);
         if (raw == null) return null;
         PendingSipInvite pending = com.alibaba.fastjson2.JSON.parseObject((String) raw, PendingSipInvite.class);
-        return pending.getBinding().matches(response) ? pending : null;
+        return rejection ? (pending.getBinding().matchesHeaders(response) ? pending : null)
+                : (pending.getBinding().matches(response) ? pending : null);
     }
 
     /** Restore the actual To-tag and transaction from headers; malformed/absent SDP cannot erase a SIP dialog. */
@@ -212,10 +218,13 @@ public class SipInviteSessionManager {
         SsrcTransaction stream = getSsrcTransactionByStream(owned.getApp(), owned.getStream());
         SsrcTransaction call = getSsrcTransactionByCallId(owned.getCallId());
         if ((stream != null && !sameDialog(owned, stream)) || (call != null && !sameDialog(owned, call))) return null;
+        // A real dialog supersedes any earlier provisional refusal of the same attempt.
+        Object rejected = redisTemplate.opsForHash().get(recoveryKey("invite-rejected"), owned.getApp() + ":" + owned.getStream());
         return SipRedisCompareAndSet.apply(redisTemplate,
                 new SipRedisCompareAndSet.Change(streamKey(), owned.getApp() + owned.getStream(), stream, owned),
                 new SipRedisCompareAndSet.Change(callKey(), owned.getCallId(), call, owned),
                 new SipRedisCompareAndSet.Change(recoveryKey("bye-confirmed"), identity, null, null),
+                new SipRedisCompareAndSet.Change(recoveryKey("invite-rejected"), owned.getApp() + ":" + owned.getStream(), rejected, null),
                 new SipRedisCompareAndSet.Change(recoveryKey("peer-bye"), identity, null, null)) ? owned : null;
     }
 
@@ -266,6 +275,39 @@ public class SipInviteSessionManager {
         return isByeConfirmed(owned) ? owned : null;
     }
 
+    /** Explicit final INVITE rejection means no dialog was established; timeouts and lost replies are NOT evidence. */
+    public boolean rememberInviteRejection(gov.nist.javax.sip.message.SIPResponse response) {
+        PendingSipInvite pending = matchPendingInvite(response, true);
+        if (pending == null) return false;
+        int status = response.getStatusCode();
+        // 401/407 are retryable challenges, not a final refusal of this generation.
+        if (status == javax.sip.message.Response.UNAUTHORIZED || status == javax.sip.message.Response.PROXY_AUTHENTICATION_REQUIRED) return false;
+        com.alibaba.fastjson2.JSONObject snapshot = new com.alibaba.fastjson2.JSONObject();
+        snapshot.put("binding", pending.getBinding()); snapshot.put("pending", pending); snapshot.put("status", status);
+        String key = recoveryKey("invite-rejected"), field = pending.getApp() + ":" + pending.getStream();
+        Object before = redisTemplate.opsForHash().get(key, field);
+        if (before != null) {
+            com.alibaba.fastjson2.JSONObject existing = com.alibaba.fastjson2.JSON.parseObject((String) before);
+            PendingSipInvite prior = existing.getObject("pending", PendingSipInvite.class);
+            // A different attempt on the same stream must not be overwritten by a stale rejection.
+            return prior != null && java.util.Objects.equals(prior.getBinding().getCallId(), pending.getBinding().getCallId())
+                    && java.util.Objects.equals(prior.getTimeoutToken(), pending.getTimeoutToken());
+        }
+        if (SipRedisCompareAndSet.apply(redisTemplate,
+                new SipRedisCompareAndSet.Change(key, field, null, snapshot.toJSONString()))) return true;
+        return isInviteRejected(pending.getNodeId(), pending.getApp(), pending.getStream(), pending.getTimeoutToken());
+    }
+
+    /** Read-only: this exact allocation attempt was definitively refused before any dialog existed. */
+    public boolean isInviteRejected(String nodeId, String app, String stream, String allocationToken) {
+        Object raw = redisTemplate.opsForHash().get(recoveryKey("invite-rejected"), app + ":" + stream);
+        if (raw == null) return false;
+        PendingSipInvite prior = com.alibaba.fastjson2.JSON.parseObject((String) raw).getObject("pending", PendingSipInvite.class);
+        return prior != null && java.util.Objects.equals(prior.getNodeId(), nodeId)
+                && java.util.Objects.equals(prior.getApp(), app) && java.util.Objects.equals(prior.getStream(), stream)
+                && java.util.Objects.equals(prior.getTimeoutToken(), allocationToken);
+    }
+
     /** A receipt proves this exact dialog, not a successful send or another allocation with the same Call-ID. */
     public boolean isByeConfirmed(SsrcTransaction expected) {
         if (expected == null || expected.getSipTransactionInfo() == null) return false;

+ 8 - 2
video-service/src/main/java/com/ruoyi/wvp/gb28181/session/SipRequestBinding.java

@@ -33,11 +33,17 @@ public class SipRequestBinding {
 
     boolean matches(SIPResponse response) {
         return response != null && response.getStatusCode() >= 200 && response.getStatusCode() < 300
+                && matchesHeaders(response) && present(response.getToTag())
+                && (Request.INVITE.equals(method) || Objects.equals(toTag, response.getToTag()));
+    }
+
+    /** Correlation only: used to attribute a final rejection, which by definition is not 2xx. */
+    boolean matchesHeaders(SIPResponse response) {
+        return response != null
                 && response.getCallIdHeader() != null && response.getCSeqHeader() != null
                 && response.getTopmostViaHeader() != null && Objects.equals(callId, response.getCallIdHeader().getCallId())
                 && cseq == response.getCSeqHeader().getSeqNumber() && Objects.equals(method, response.getCSeqHeader().getMethod())
-                && Objects.equals(fromTag, response.getFromTag()) && Objects.equals(viaBranch, response.getTopmostViaHeader().getBranch())
-                && present(response.getToTag()) && (Request.INVITE.equals(method) || Objects.equals(toTag, response.getToTag()));
+                && Objects.equals(fromTag, response.getFromTag()) && Objects.equals(viaBranch, response.getTopmostViaHeader().getBranch());
     }
     String key() { return callId.length() + ":" + callId + ":" + cseq; }
     static String key(SIPResponse response) {

+ 6 - 0
video-service/src/main/java/com/ruoyi/wvp/gb28181/transmit/SIPProcessorObserver.java

@@ -145,6 +145,12 @@ public class SIPProcessorObserver implements ISIPProcessorObserver {
                     && (sessionManager == null || !sessionManager.hasByeRequest(response))) {
                 responseEvent.getDialog().delete();
             }
+            // A final refusal of a managed INVITE is durable evidence that no dialog was
+            // established; timeouts and lost replies are never recorded this way.
+            if (sessionManager != null && javax.sip.message.Request.INVITE.equals(response.getCSeqHeader().getMethod())) {
+                try { sessionManager.rememberInviteRejection(response); }
+                catch (RuntimeException ignored) { /* Rejection evidence is optional; it never blocks transport. */ }
+            }
         }
 
 

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

@@ -312,6 +312,29 @@ class LateSipRecoveryTest {
         assertEquals(1, published.get()); assertNotNull(external.manager().getSsrcTransactionByCallId("call-1"));
     }
 
+    @Test void finalInviteRefusalIsDurableButTimeoutChallengeAndLostReplyAreNot() throws Exception {
+        RedisBytes external = new RedisBytes();
+        com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class));
+        assertTrue(external.manager().rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
+                "node-a", "device-a", 7, "channel-a", allocation(), "127.0.0.1", 1L));
+        com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver observer = new com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver();
+        ReflectionTestUtils.setField(observer, "sessionManager", external.manager());
+        ReflectionTestUtils.setField(observer, "sipSubscribe", new com.ruoyi.wvp.gb28181.event.SipSubscribe());
+
+        // A retryable authentication challenge is not a final refusal.
+        observer.processResponse(new javax.sip.ResponseEvent(this, null, null,
+                response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1", 401)));
+        assertFalse(external.manager().isInviteRejected("node-a", "rtp", allocation().getStream(), "timeout-1"));
+        assertFalse(external.manager().rememberInviteRejection(response("INVITE", "other-call", 9, "z9hG4bK-invite", "to-1", 486)));
+
+        observer.processResponse(new javax.sip.ResponseEvent(this, null, null,
+                response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1", 486)));
+        assertTrue(external.manager().isInviteRejected("node-a", "rtp", allocation().getStream(), "timeout-1"));
+        // A later real 2xx must still restore the dialog and supersede the provisional refusal.
+        assertNotNull(external.manager().restoreManagedInvite(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
+        assertFalse(external.manager().isInviteRejected("node-a", "rtp", allocation().getStream(), "timeout-1"));
+    }
+
     @Test void commanderNeverSendsInviteWhenPreDispatchPersistenceFails() throws Exception {
         RedisBytes external = new RedisBytes(); external.rejectCas = true;
         com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
@@ -363,8 +386,12 @@ class LateSipRecoveryTest {
                 method + " sip:channel@127.0.0.2:5060 SIP/2.0\r\n" + headers(method, call, seq, branch, toTag));
     }
     static gov.nist.javax.sip.message.SIPResponse response(String method, String call, long seq, String branch, String toTag) throws Exception {
+        return response(method, call, seq, branch, toTag, 200);
+    }
+    static gov.nist.javax.sip.message.SIPResponse response(String method, String call, long seq, String branch, String toTag,
+                                                          int status) throws Exception {
         return (gov.nist.javax.sip.message.SIPResponse) javax.sip.SipFactory.getInstance().createMessageFactory()
-                .createResponse("SIP/2.0 200 OK\r\n" + headers(method, call, seq, branch, toTag));
+                .createResponse("SIP/2.0 " + status + " response\r\n" + headers(method, call, seq, branch, toTag));
     }
     static String headers(String method, String call, long seq, String branch, String toTag) {
         return "Via: SIP/2.0/UDP 127.0.0.1:5060;branch=" + branch + "\r\n"

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

@@ -102,6 +102,35 @@ class VideoStopReceiptRestartTest {
         assertEquals(1, world.closeRequests.size());
     }
 
+    @Test void ssrcRenegotiationKeepsTheOriginalPoolIdentityForCleanup() throws Exception {
+        External world = new External();
+        Instance instance = new Instance(world);
+        String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
+        SSRCInfo original = instance.open(LEGACY);
+        assertNotNull(original);
+        String negotiated = "9777777777";
+        // Device-selected SSRC: the receipt keeps the pool number but accepts the real current SSRC.
+        assertTrue(instance.receipts.recordNegotiatedSsrc(world.node.getId(), LEGACY, original, negotiated, false));
+        SSRCInfo current = new SSRCInfo(original.getPort(), negotiated, "rtp", LEGACY, original.getTimeOutTaskKey());
+        new Instance(world).rtp.closeRTPServer(world.node, current);
+        assertEquals(1, world.closeRequests.size());
+        // The returned number is the original pool value; a device-negotiated SSRC is never returned.
+        assertTrue(world.ssrcRedis.strings().opsForSet().isMember(pool, original.getSsrc().substring(1)));
+        assertFalse(world.ssrcRedis.strings().opsForSet().isMember(pool, negotiated.substring(1)));
+    }
+
+    @Test void staleAllocationTokenCannotAnnotateANewerSameNameAllocation() throws Exception {
+        External world = new External();
+        Instance instance = new Instance(world);
+        SSRCInfo original = instance.open(LEGACY);
+        instance.rtp.closeRTPServer(world.node, original);
+        SSRCInfo replacement = instance.open(LEGACY);
+        assertNotEquals(original.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
+        assertFalse(instance.receipts.recordNegotiatedSsrc(world.node.getId(), LEGACY, original, "9666666666", false));
+        new Instance(world).rtp.closeRTPServer(world.node, replacement);
+        assertEquals(2, world.closeRequests.size());
+    }
+
     @Test void managedStopRecoversOriginalDialogAfterByeReceiptAndLiveDialogDeletion() throws Exception {
         External world = new External(); Instance first = new Instance(world);
         first.managed();