| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442 |
- package com.zksy.video.lifecycle;
- import com.ruoyi.wvp.common.InviteSessionType;
- import com.ruoyi.wvp.conf.UserSetting;
- import com.ruoyi.wvp.gb28181.bean.*;
- import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
- import com.ruoyi.wvp.service.bean.SSRCInfo;
- import org.junit.jupiter.api.Test;
- import org.springframework.data.redis.connection.RedisConnection;
- import org.springframework.data.redis.connection.ReturnType;
- import org.springframework.data.redis.core.*;
- import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
- import org.springframework.test.util.ReflectionTestUtils;
- import java.nio.charset.StandardCharsets;
- import java.util.*;
- import static org.junit.jupiter.api.Assertions.*;
- import static org.mockito.ArgumentMatchers.*;
- import static org.mockito.Mockito.*;
- /** External Redis substitute retains serialized bytes, never references to application objects. */
- class LateSipRecoveryTest {
- @Test void adoptionSurvivesManagerReconstructionAndDoesNotShareMutableDialogs() {
- RedisBytes external = new RedisBytes();
- SipInviteSessionManager first = external.manager();
- SsrcTransaction original = dialog("legacy", "call-1");
- SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1");
- first.put(original);
- assertTrue(first.retainAdopted(original, allocation));
- original.getSipTransactionInfo().setToTag("mutated-after-write");
- allocation.setTimeOutTaskKey("mutated-after-write");
- SipInviteSessionManager restarted = external.manager();
- SsrcTransaction persisted = restarted.getSsrcTransactionByCallId("call-1");
- assertEquals("to-1", persisted.getSipTransactionInfo().getToTag());
- assertTrue(restarted.isAdopted(persisted));
- assertTrue(restarted.isAdoptedRtp("node-a", "call-1",
- new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1")));
- assertFalse(restarted.isAdoptedRtp("node-b", "call-1",
- new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1")));
- }
- @Test void realByeAfterCallbackLossConfirmsOnlyTheOriginalAllocationAcrossReconstruction() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager first = external.manager();
- SsrcTransaction original = dialog("managed_11111111111111111111111111111111", "call-1"); first.put(original);
- javax.sip.message.Request request = request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1");
- assertTrue(first.rememberBye(request, original));
- assertFalse(external.manager().isByeConfirmed(original));
- assertNull(external.manager().confirmBye(response("BYE", "call-1", 42, "z9hG4bK-bye", "to-1")));
- assertNull(external.manager().confirmBye(response("INVITE", "call-1", 41, "z9hG4bK-bye", "to-1")));
- assertNull(external.manager().confirmBye(response("BYE", "call-1", 41, "z9hG4bK-wrong", "to-1")));
- assertNull(external.manager().confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "other-dialog")));
- SipInviteSessionManager restarted = external.manager();
- assertNotNull(restarted.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
- assertTrue(external.manager().isByeConfirmed(original));
- assertTrue(external.manager().isSipTerminated(original));
- assertTrue(restarted.removeManagedIfSame(original));
- SsrcTransaction replacement = dialog(original.getStream(), "call-1"); replacement.setSsrc("9999999999");
- replacement.getSipTransactionInfo().setToTag("to-new"); restarted.put(replacement);
- assertNotNull(restarted.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
- assertFalse(restarted.removeManagedIfSame(original));
- assertFalse(external.manager().isByeConfirmed(replacement));
- assertEquals("to-new", restarted.getSsrcTransactionByStream("rtp", original.getStream()).getSipTransactionInfo().getToTag());
- }
- @Test void pendingInviteRecoversFromBytesWithoutCallbackAndRejectsForeignResponseBindings() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager first = external.manager();
- SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1");
- assertTrue(first.rememberInvite(request("INVITE", "invite-1", 9, "z9hG4bK-invite", null),
- "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
- SipInviteSessionManager restarted = external.manager();
- assertNull(restarted.restoreManagedInvite(response("INVITE", "other-call", 9, "z9hG4bK-invite", "to-1")));
- assertNull(restarted.restoreManagedInvite(response("INVITE", "invite-1", 10, "z9hG4bK-invite", "to-1")));
- assertNull(restarted.restoreManagedInvite(response("INVITE", "invite-1", 9, "z9hG4bK-foreign", "to-1")));
- gov.nist.javax.sip.message.SIPResponse wrongFrom = response("INVITE", "invite-1", 9, "z9hG4bK-invite", "to-1");
- wrongFrom.getFrom().setTag("foreign-from"); assertNull(restarted.restoreManagedInvite(wrongFrom));
- gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "invite-1", 9, "z9hG4bK-invite", "to-1");
- SsrcTransaction restored = restarted.restoreManagedInvite(actual);
- assertNotNull(restored); assertEquals("node-a", restored.getMediaServerId()); assertEquals("device-a", restored.getDeviceId());
- assertEquals("to-1", restored.getSipTransactionInfo().getToTag()); assertEquals("1234567890", restored.getSsrc());
- assertEquals("timeout-1", restarted.matchPendingInvite(actual).getTimeoutToken());
- assertEquals("127.0.0.1", restarted.matchPendingInvite(actual).getLocalIp());
- assertTrue(restarted.matchPendingInvite(actual).isExpired());
- SsrcTransaction replacement = dialog(allocation.getStream(), "new-call"); restarted.put(replacement);
- assertNull(restarted.restoreManagedInvite(actual));
- assertEquals("new-call", restarted.getSsrcTransactionByStream("rtp", allocation.getStream()).getCallId());
- }
- @Test void observerRecordsLateByeWithEmptySubscriptionsBeforeDeletingTheDialog() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); sessions.put(owned);
- assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
- com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver observer = new com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver();
- ReflectionTestUtils.setField(observer, "sessionManager", external.manager());
- com.ruoyi.wvp.gb28181.event.SipSubscribe expired = new com.ruoyi.wvp.gb28181.event.SipSubscribe();
- expired.addSubscribe("call-141", com.ruoyi.wvp.gb28181.event.sip.SipEvent.getInstance("call-141", result -> fail("expired callback must not execute"), null, -1));
- expired.execute(); assertTrue(expired.isEmpty());
- ReflectionTestUtils.setField(observer, "sipSubscribe", expired);
- javax.sip.Dialog sipDialog = mock(javax.sip.Dialog.class);
- doAnswer(i -> { assertTrue(external.manager().isByeConfirmed(owned)); return null; }).when(sipDialog).delete();
- observer.processResponse(new javax.sip.ResponseEvent(this, null, sipDialog,
- response("BYE", "call-1", 41, "z9hG4bK-wrong", "to-1")));
- verify(sipDialog, never()).delete(); assertFalse(sessions.isByeConfirmed(owned));
- observer.processResponse(new javax.sip.ResponseEvent(this, null, sipDialog,
- response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
- verify(sipDialog).delete(); assertTrue(external.manager().isByeConfirmed(owned));
- assertNull(external.manager().getSsrcTransactionByStream("rtp", owned.getStream()));
- }
- @Test void deletionCasCannotEraseAReplacementFromAnotherServiceInstance() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); sessions.put(owned);
- assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
- assertNotNull(sessions.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
- SsrcTransaction replacement = dialog(owned.getStream(), "call-2");
- external.beforeCas = () -> external.manager().put(replacement);
- assertFalse(sessions.removeManagedIfSame(owned));
- assertEquals("call-2", sessions.getSsrcTransactionByStream("rtp", owned.getStream()).getCallId());
- assertNotNull(sessions.getSsrcTransactionByCallId("call-1"), "CAS loses both deletes, not only the stream delete");
- }
- @Test void inviteRetransmitAfterConfirmedByeDoesNotResurrectTheAllocation() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1");
- assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
- "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
- gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
- SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
- assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
- assertNotNull(sessions.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
- assertTrue(sessions.removeManagedIfSame(owned));
- assertNull(external.manager().restoreManagedInvite(actual));
- assertNull(external.manager().getSsrcTransactionByStream("rtp", allocation.getStream()));
- }
- @Test void lateInviteWithoutCallbackAcksMalformedSdpThenStopsOnlyPersistedOriginalSource() throws Exception {
- InviteFixture f = new InviteFixture();
- gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
- actual.setContent("unparseable SDP\r\ny=do-not-associate-by-body", javax.sip.SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
- f.processor.process(f.event(actual));
- org.mockito.InOrder order = inOrder(f.sender, f.play);
- order.verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
- order.verify(f.play).stopManaged(f.node, f.device, f.channel, f.stream);
- SsrcTransaction persisted = f.external.manager().getSsrcTransactionByStream("rtp", f.stream);
- assertNotNull(persisted); assertEquals("to-1", persisted.getSipTransactionInfo().getToTag());
- assertEquals("1234567890", persisted.getSsrc());
- verify(f.media, never()).getDefaultMediaServer();
- verify(f.channels).getOneForSource("device-a", "channel-a");
- }
- @Test void unrelatedInviteStillGetsLegacyAckButCannotRecoverOrStopAnOwnedStream() throws Exception {
- InviteFixture f = new InviteFixture();
- f.processor.process(f.event(response("INVITE", "foreign-call", 9, "z9hG4bK-invite", "to-1")));
- verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
- verifyNoInteractions(f.play, f.media, f.channels, f.devices);
- assertNull(f.external.manager().getSsrcTransactionByStream("rtp", f.stream));
- }
- @Test void retransmittedInviteForAnActiveGenerationOnlyResendsAck() throws Exception {
- InviteFixture f = new InviteFixture();
- f.generation.setStatus("ACTIVE");
- // The original start deadline is old, but healthy playback is not a new start attempt.
- f.processor.process(f.event(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
- verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
- verifyNoInteractions(f.play);
- }
- @Test void sourceScopedLookupMismatchRetainsTheDialogWithoutStoppingAnotherSource() throws Exception {
- InviteFixture f = new InviteFixture(); f.channel.setId(99);
- f.processor.process(f.event(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
- verifyNoInteractions(f.play); assertNotNull(f.external.manager().getSsrcTransactionByStream("rtp", f.stream));
- }
- @Test void peerByePersistsIndependentTerminationAndFencesInviteRetransmit() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- SSRCInfo allocation = allocation();
- assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
- "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
- gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
- SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
- assertTrue(sessions.rememberPeerBye(peerBye(owned), owned));
- SipInviteSessionManager restarted = external.manager();
- assertTrue(restarted.isSipTerminated(owned));
- assertFalse(restarted.isByeConfirmed(owned), "peer BYE is not an outgoing BYE response");
- assertTrue(restarted.removeManagedIfSame(owned));
- assertNull(external.manager().restoreManagedInvite(actual));
- assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
- }
- @Test void malformedForeignAndReplacedPeerRequestsCannotBecomeTerminationEvidence() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- SsrcTransaction owned = dialog("legacy", "call-1");
- assertFalse(sessions.rememberPeerBye(peerBye(owned), owned), "unknown dialogs cannot acquire peer evidence");
- sessions.put(owned);
- gov.nist.javax.sip.message.SIPRequest wrongTags = peerBye(owned);
- wrongTags.getFrom().setTag("foreign");
- assertFalse(sessions.rememberPeerBye(wrongTags, owned));
- gov.nist.javax.sip.message.SIPRequest wrongCall = peerBye(owned);
- wrongCall.getCallIdHeader().setCallId("foreign-call");
- assertFalse(sessions.rememberPeerBye(wrongCall, owned));
- gov.nist.javax.sip.message.SIPRequest wrongCseq = peerBye(owned);
- wrongCseq.getCSeqHeader().setMethod("INVITE");
- assertFalse(sessions.rememberPeerBye(wrongCseq, owned));
- gov.nist.javax.sip.message.SIPRequest noBranch = peerBye(owned);
- noBranch.getTopmostViaHeader().removeParameter("branch");
- assertFalse(sessions.rememberPeerBye(noBranch, owned));
- assertFalse(sessions.rememberPeerBye(request("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1"), owned));
- SsrcTransaction replacement = dialog("legacy", "call-1");
- replacement.getSipTransactionInfo().setToTag("new-tags");
- external.beforeCas = () -> external.manager().put(replacement);
- assertFalse(sessions.rememberPeerBye(peerBye(owned), owned));
- assertFalse(external.manager().isSipTerminated(owned));
- assertFalse(external.manager().isSipTerminated(replacement));
- assertFalse(sessions.rememberPeerBye(peerBye(owned), replacement));
- assertFalse(sessions.removeIfSame(owned));
- assertEquals("new-tags", external.manager().getSsrcTransactionByCallId("call-1").getSipTransactionInfo().getToTag());
- }
- @Test void snapshotDeleteIsAtomicAcrossBothIndexesWithoutInventingProtocolEvidence() {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- SsrcTransaction owned = dialog("legacy", "call-1"); sessions.put(owned);
- SsrcTransaction replacement = dialog("legacy", "call-1");
- replacement.getSipTransactionInfo().setToTag("new-tags");
- external.beforeCas = () -> external.manager().put(replacement);
- assertFalse(sessions.removeIfSame(owned));
- assertTrue(SipInviteSessionManager.sameDialog(replacement, external.manager().getSsrcTransactionByCallId("call-1")));
- assertTrue(SipInviteSessionManager.sameDialog(replacement, external.manager().getSsrcTransactionByStream("rtp", "legacy")));
- assertTrue(external.manager().removeIfSame(replacement));
- assertFalse(external.manager().isSipTerminated(replacement), "offline cleanup is not SIP termination");
- assertFalse(external.manager().isByeConfirmed(replacement));
- }
- @Test void peerMarkerArrivingBetweenRestoreReadAndCasCannotResurrectDialog() throws Exception {
- RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
- assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
- "node-a", "device-a", 7, "channel-a", allocation(), "127.0.0.1", 1L));
- gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
- SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
- gov.nist.javax.sip.message.SIPRequest peer = peerBye(owned);
- external.beforeCas = () -> {
- assertTrue(external.manager().rememberPeerBye(peer, owned));
- assertTrue(external.manager().removeIfSame(owned));
- };
- assertNull(sessions.restoreManagedInvite(actual));
- assertTrue(external.manager().isSipTerminated(owned));
- assertNull(external.manager().getSsrcTransactionByStream("rtp", owned.getStream()));
- }
- static gov.nist.javax.sip.message.SIPRequest peerBye(SsrcTransaction owned) throws Exception {
- gov.nist.javax.sip.message.SIPRequest peer = (gov.nist.javax.sip.message.SIPRequest)
- request("BYE", owned.getCallId(), 77, "z9hG4bK-peer", owned.getSipTransactionInfo().getFromTag());
- peer.getFrom().setTag(owned.getSipTransactionInfo().getToTag());
- return peer;
- }
- static class InviteFixture {
- final RedisBytes external = new RedisBytes();
- final String stream = "managed_11111111111111111111111111111111";
- final com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor processor = new com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor();
- final com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
- final com.ruoyi.wvp.gb28181.service.IPlayService play = mock(com.ruoyi.wvp.gb28181.service.IPlayService.class);
- final com.ruoyi.wvp.media.service.IMediaServerService media = mock(com.ruoyi.wvp.media.service.IMediaServerService.class);
- final com.ruoyi.wvp.gb28181.service.IDeviceChannelService channels = mock(com.ruoyi.wvp.gb28181.service.IDeviceChannelService.class);
- final com.ruoyi.wvp.storager.IRedisCatchStorage devices = mock(com.ruoyi.wvp.storager.IRedisCatchStorage.class);
- final com.ruoyi.wvp.media.bean.MediaServer node = new com.ruoyi.wvp.media.bean.MediaServer();
- final Device device = new Device(); final DeviceChannel channel = new DeviceChannel();
- final VideoLifecycleStore lifecycle = mock(VideoLifecycleStore.class);
- final VideoLifecycleRecord generation = new VideoLifecycleRecord();
- InviteFixture() throws Exception {
- generation.setGeneration("11111111-1111-1111-1111-111111111111");
- generation.setStatus("STARTING"); generation.setDeadline(1L);
- when(lifecycle.find(generation.getGeneration())).thenReturn(generation);
- SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", stream, "timeout-1");
- 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));
- node.setId("node-a"); device.setDeviceId("device-a"); channel.setId(7); channel.setDeviceId("channel-a");
- when(media.getOne("node-a")).thenReturn(node); when(devices.getDevice("device-a")).thenReturn(device);
- when(channels.getOneForSource("device-a", "channel-a")).thenReturn(channel);
- com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
- when(headers.createAckRequest(anyString(), any(), any())).thenReturn(request("ACK", "call-1", 9, "z9hG4bK-ack", "to-1"));
- ReflectionTestUtils.setField(processor, "sessionManager", external.manager());
- ReflectionTestUtils.setField(processor, "sipSender", sender); ReflectionTestUtils.setField(processor, "headerProvider", headers);
- ReflectionTestUtils.setField(processor, "playService", play); ReflectionTestUtils.setField(processor, "mediaServerService", media);
- ReflectionTestUtils.setField(processor, "redisCatchStorage", devices); ReflectionTestUtils.setField(processor, "deviceChannelService", channels);
- ReflectionTestUtils.setField(processor, "videoLifecycleStore", lifecycle);
- }
- gov.nist.javax.sip.ResponseEventExt event(gov.nist.javax.sip.message.SIPResponse response) throws Exception {
- gov.nist.javax.sip.message.SIPResponse received = spy(response);
- when(received.getLocalAddress()).thenReturn(java.net.InetAddress.getByName("127.0.0.1"));
- gov.nist.javax.sip.ResponseEventExt event = mock(gov.nist.javax.sip.ResponseEventExt.class);
- when(event.getResponse()).thenReturn(received); when(event.getRemoteIpAddress()).thenReturn("127.0.0.2"); when(event.getRemotePort()).thenReturn(5060);
- return event;
- }
- }
- @Test void commanderPersistsBeforeInviteSendAndOriginalCallbackAcceptsOnlyBoundResponse() throws Exception {
- RedisBytes external = new RedisBytes();
- com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
- com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
- java.util.concurrent.atomic.AtomicReference<com.ruoyi.wvp.gb28181.event.SipSubscribe.Event> callback = new java.util.concurrent.atomic.AtomicReference<>();
- doAnswer(i -> {
- assertNotNull(external.manager().getPendingInviteByStream("rtp", "managed_11111111111111111111111111111111"));
- callback.set(i.getArgument(3)); return null;
- }).when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any(), anyLong());
- java.util.concurrent.atomic.AtomicInteger published = new java.util.concurrent.atomic.AtomicInteger();
- commander.playStreamCmd(node(), allocation(), device(), channel(), result -> published.incrementAndGet(), result -> { }, 60000L);
- callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
- response("INVITE", "call-1", 9, "z9hG4bK-wrong", "to-1"))));
- assertEquals(0, published.get()); assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
- callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
- response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1"))));
- assertEquals(1, published.get()); assertNotNull(external.manager().getSsrcTransactionByCallId("call-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);
- com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
- assertThrows(javax.sip.SipException.class, () -> commander.playStreamCmd(node(), allocation(), device(), channel(), result -> { }, result -> { }, 60000L));
- verify(sender, never()).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any(), anyLong());
- }
- @Test void commanderByeCallbackPersistsConfirmationBeforeNotifyingCaller() throws Exception {
- RedisBytes external = new RedisBytes(); SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); external.manager().put(owned);
- com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
- com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
- java.util.concurrent.atomic.AtomicReference<com.ruoyi.wvp.gb28181.event.SipSubscribe.Event> callback = new java.util.concurrent.atomic.AtomicReference<>();
- doAnswer(i -> { assertTrue(external.manager().hasByeRequest(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"))); callback.set(i.getArgument(3)); return null; })
- .when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any());
- java.util.concurrent.atomic.AtomicInteger notified = new java.util.concurrent.atomic.AtomicInteger();
- commander.streamByeCmd(device(), "channel-a", "rtp", owned.getStream(), "call-1", result -> {
- assertTrue(external.manager().isByeConfirmed(owned)); notified.incrementAndGet();
- });
- assertFalse(external.manager().isByeConfirmed(owned));
- callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
- response("INVITE", "call-1", 41, "z9hG4bK-bye", "to-1"))));
- assertEquals(0, notified.get());
- callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
- response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"))));
- assertEquals(1, notified.get()); assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
- }
- static com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander(RedisBytes external, com.ruoyi.wvp.gb28181.transmit.SIPSender sender) throws Exception {
- com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = new com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander();
- com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
- when(headers.createInviteRequest(any(), anyString(), anyString(), anyString(), anyString(), isNull(), anyString(), any()))
- .thenReturn(request("INVITE", "call-1", 9, "z9hG4bK-invite", null));
- when(headers.createByteRequest(any(), anyString(), any())).thenReturn(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"));
- com.ruoyi.wvp.gb28181.SipLayer layer = mock(com.ruoyi.wvp.gb28181.SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
- UserSetting settings = new UserSetting(); settings.setSeniorSdp(false);
- ReflectionTestUtils.setField(commander, "sessionManager", external.manager()); ReflectionTestUtils.setField(commander, "sipSender", sender);
- ReflectionTestUtils.setField(commander, "headerProvider", headers); ReflectionTestUtils.setField(commander, "sipLayer", layer);
- ReflectionTestUtils.setField(commander, "videoLifecycleStore", mock(VideoLifecycleStore.class)); ReflectionTestUtils.setField(commander, "userSetting", settings);
- return commander;
- }
- static Device device() { Device d = new Device(); d.setDeviceId("device-a"); d.setStreamMode("UDP"); return d; }
- static DeviceChannel channel() { DeviceChannel c = new DeviceChannel(); c.setId(7); c.setDeviceId("channel-a"); return c; }
- static com.ruoyi.wvp.media.bean.MediaServer node() { com.ruoyi.wvp.media.bean.MediaServer n = new com.ruoyi.wvp.media.bean.MediaServer(); n.setId("node-a"); n.setSdpIp("127.0.0.1"); return n; }
- static SSRCInfo allocation() { return new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1"); }
- static javax.sip.message.Request request(String method, String call, long seq, String branch, String toTag) throws Exception {
- return javax.sip.SipFactory.getInstance().createMessageFactory().createRequest(
- 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 (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));
- }
- 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"
- + "From: <sip:server@127.0.0.1>;tag=from-1\r\nTo: <sip:channel@127.0.0.2>" + (toTag == null ? "" : ";tag=" + toTag)
- + "\r\nCall-ID: " + call + "\r\nCSeq: " + seq + " " + method + "\r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n";
- }
- static SsrcTransaction dialog(String stream, String call) {
- SsrcTransaction tx = new SsrcTransaction();
- tx.setDeviceId("device-a"); tx.setChannelId(7); tx.setApp("rtp"); tx.setStream(stream);
- tx.setMediaServerId("node-a"); tx.setSsrc("1234567890"); tx.setCallId(call); tx.setType(InviteSessionType.PLAY);
- SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(call); sip.setFromTag("from-1");
- sip.setToTag("to-1"); sip.setViaBranch("z9hG4bK-invite"); tx.setSipTransactionInfo(sip); return tx;
- }
- static class RedisBytes {
- final Map<String, Map<String, byte[]>> data = new HashMap<>();
- final StringRedisSerializer strings = new StringRedisSerializer();
- final GenericJackson2JsonRedisSerializer values = new GenericJackson2JsonRedisSerializer();
- Runnable beforeCas;
- boolean rejectCas;
- @SuppressWarnings({"unchecked", "rawtypes"})
- RedisTemplate<Object,Object> client() {
- RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
- HashOperations<Object,Object,Object> hashes = mock(HashOperations.class);
- when(redis.opsForHash()).thenReturn(hashes);
- when(redis.getKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
- when(redis.getHashKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
- doReturn(values).when(redis).getHashValueSerializer();
- doAnswer(i -> { put(i.getArgument(0).toString(), i.getArgument(1).toString(), values.serialize(i.getArgument(2))); return null; })
- .when(hashes).put(any(), any(), any());
- when(hashes.get(any(), any())).thenAnswer(i -> values.deserialize(get(i.getArgument(0).toString(), i.getArgument(1).toString())));
- when(hashes.values(any())).thenAnswer(i -> {
- List<Object> result = new ArrayList<>();
- for (byte[] bytes : data.getOrDefault(i.getArgument(0).toString(), Collections.emptyMap()).values()) result.add(values.deserialize(bytes));
- return result;
- });
- when(hashes.delete(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0).toString(), Collections.emptyMap()).remove(i.getArgument(1).toString()) == null ? 0L : 1L);
- RedisConnection connection = mock(RedisConnection.class);
- when(redis.execute(any(RedisCallback.class))).thenAnswer(i -> ((RedisCallback<?>) i.getArgument(0)).doInRedis(connection));
- when(connection.eval(any(byte[].class), eq(ReturnType.INTEGER), anyInt(), org.mockito.ArgumentMatchers.<byte[][]>any())).thenAnswer(i -> {
- if (rejectCas) return 0L;
- if (beforeCas != null) { Runnable race = beforeCas; beforeCas = null; race.run(); }
- int n = i.getArgument(2);
- Object[] invocation = i.getArguments();
- byte[][] args = invocation.length == 4 && invocation[3] instanceof byte[][]
- ? (byte[][]) invocation[3] : Arrays.copyOfRange(invocation, 3, invocation.length, byte[][].class);
- // Emulate the generic compare-all-then-write-all Lua at the external Redis boundary.
- synchronized (data) {
- for (int k = 0; k < n; k++) {
- int a = n + k * 5;
- byte[] expected = "1".equals(text(args[a+1])) ? args[a+2] : null;
- if (!Arrays.equals(expected, get(text(args[k]), text(args[a])))) return 0L;
- }
- for (int k = 0; k < n; k++) {
- int a = n + k * 5;
- if ("1".equals(text(args[a+3]))) put(text(args[k]), text(args[a]), args[a+4]);
- else data.computeIfAbsent(text(args[k]), unused -> new HashMap<>()).remove(text(args[a]));
- }
- return 1L;
- }
- });
- return redis;
- }
- SipInviteSessionManager manager() {
- SipInviteSessionManager result = new SipInviteSessionManager();
- UserSetting settings = new UserSetting(); settings.setServerId("late-test");
- ReflectionTestUtils.setField(result, "userSetting", settings);
- ReflectionTestUtils.setField(result, "redisTemplate", client()); return result;
- }
- byte[] get(String key, String field) { byte[] bytes = data.getOrDefault(key, Collections.emptyMap()).get(field); return bytes == null ? null : bytes.clone(); }
- void put(String key, String field, byte[] bytes) { data.computeIfAbsent(key, unused -> new HashMap<>()).put(field, bytes.clone()); }
- static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
- }
- }
|