LateSipRecoveryTest.java 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. package com.zksy.video.lifecycle;
  2. import com.ruoyi.wvp.common.InviteSessionType;
  3. import com.ruoyi.wvp.conf.UserSetting;
  4. import com.ruoyi.wvp.gb28181.bean.*;
  5. import com.ruoyi.wvp.gb28181.session.SipInviteSessionManager;
  6. import com.ruoyi.wvp.service.bean.SSRCInfo;
  7. import org.junit.jupiter.api.Test;
  8. import org.springframework.data.redis.connection.RedisConnection;
  9. import org.springframework.data.redis.connection.ReturnType;
  10. import org.springframework.data.redis.core.*;
  11. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  12. import org.springframework.data.redis.serializer.StringRedisSerializer;
  13. import org.springframework.test.util.ReflectionTestUtils;
  14. import java.nio.charset.StandardCharsets;
  15. import java.util.*;
  16. import static org.junit.jupiter.api.Assertions.*;
  17. import static org.mockito.ArgumentMatchers.*;
  18. import static org.mockito.Mockito.*;
  19. /** External Redis substitute retains serialized bytes, never references to application objects. */
  20. class LateSipRecoveryTest {
  21. @Test void adoptionSurvivesManagerReconstructionAndDoesNotShareMutableDialogs() {
  22. RedisBytes external = new RedisBytes();
  23. SipInviteSessionManager first = external.manager();
  24. SsrcTransaction original = dialog("legacy", "call-1");
  25. SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1");
  26. first.put(original);
  27. assertTrue(first.retainAdopted(original, allocation));
  28. original.getSipTransactionInfo().setToTag("mutated-after-write");
  29. allocation.setTimeOutTaskKey("mutated-after-write");
  30. SipInviteSessionManager restarted = external.manager();
  31. SsrcTransaction persisted = restarted.getSsrcTransactionByCallId("call-1");
  32. assertEquals("to-1", persisted.getSipTransactionInfo().getToTag());
  33. assertTrue(restarted.isAdopted(persisted));
  34. assertTrue(restarted.isAdoptedRtp("node-a", "call-1",
  35. new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1")));
  36. assertFalse(restarted.isAdoptedRtp("node-b", "call-1",
  37. new SSRCInfo(30000, "1234567890", "rtp", "legacy", "allocation-1")));
  38. }
  39. @Test void realByeAfterCallbackLossConfirmsOnlyTheOriginalAllocationAcrossReconstruction() throws Exception {
  40. RedisBytes external = new RedisBytes(); SipInviteSessionManager first = external.manager();
  41. SsrcTransaction original = dialog("managed_11111111111111111111111111111111", "call-1"); first.put(original);
  42. javax.sip.message.Request request = request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1");
  43. assertTrue(first.rememberBye(request, original));
  44. assertFalse(external.manager().isByeConfirmed(original));
  45. assertNull(external.manager().confirmBye(response("BYE", "call-1", 42, "z9hG4bK-bye", "to-1")));
  46. assertNull(external.manager().confirmBye(response("INVITE", "call-1", 41, "z9hG4bK-bye", "to-1")));
  47. assertNull(external.manager().confirmBye(response("BYE", "call-1", 41, "z9hG4bK-wrong", "to-1")));
  48. assertNull(external.manager().confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "other-dialog")));
  49. SipInviteSessionManager restarted = external.manager();
  50. assertNotNull(restarted.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
  51. assertTrue(external.manager().isByeConfirmed(original));
  52. assertTrue(external.manager().isSipTerminated(original));
  53. assertTrue(restarted.removeManagedIfSame(original));
  54. SsrcTransaction replacement = dialog(original.getStream(), "call-1"); replacement.setSsrc("9999999999");
  55. replacement.getSipTransactionInfo().setToTag("to-new"); restarted.put(replacement);
  56. assertNotNull(restarted.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
  57. assertFalse(restarted.removeManagedIfSame(original));
  58. assertFalse(external.manager().isByeConfirmed(replacement));
  59. assertEquals("to-new", restarted.getSsrcTransactionByStream("rtp", original.getStream()).getSipTransactionInfo().getToTag());
  60. }
  61. @Test void pendingInviteRecoversFromBytesWithoutCallbackAndRejectsForeignResponseBindings() throws Exception {
  62. RedisBytes external = new RedisBytes(); SipInviteSessionManager first = external.manager();
  63. SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1");
  64. assertTrue(first.rememberInvite(request("INVITE", "invite-1", 9, "z9hG4bK-invite", null),
  65. "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
  66. SipInviteSessionManager restarted = external.manager();
  67. assertNull(restarted.restoreManagedInvite(response("INVITE", "other-call", 9, "z9hG4bK-invite", "to-1")));
  68. assertNull(restarted.restoreManagedInvite(response("INVITE", "invite-1", 10, "z9hG4bK-invite", "to-1")));
  69. assertNull(restarted.restoreManagedInvite(response("INVITE", "invite-1", 9, "z9hG4bK-foreign", "to-1")));
  70. gov.nist.javax.sip.message.SIPResponse wrongFrom = response("INVITE", "invite-1", 9, "z9hG4bK-invite", "to-1");
  71. wrongFrom.getFrom().setTag("foreign-from"); assertNull(restarted.restoreManagedInvite(wrongFrom));
  72. gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "invite-1", 9, "z9hG4bK-invite", "to-1");
  73. SsrcTransaction restored = restarted.restoreManagedInvite(actual);
  74. assertNotNull(restored); assertEquals("node-a", restored.getMediaServerId()); assertEquals("device-a", restored.getDeviceId());
  75. assertEquals("to-1", restored.getSipTransactionInfo().getToTag()); assertEquals("1234567890", restored.getSsrc());
  76. assertEquals("timeout-1", restarted.matchPendingInvite(actual).getTimeoutToken());
  77. assertEquals("127.0.0.1", restarted.matchPendingInvite(actual).getLocalIp());
  78. assertTrue(restarted.matchPendingInvite(actual).isExpired());
  79. SsrcTransaction replacement = dialog(allocation.getStream(), "new-call"); restarted.put(replacement);
  80. assertNull(restarted.restoreManagedInvite(actual));
  81. assertEquals("new-call", restarted.getSsrcTransactionByStream("rtp", allocation.getStream()).getCallId());
  82. }
  83. @Test void observerRecordsLateByeWithEmptySubscriptionsBeforeDeletingTheDialog() throws Exception {
  84. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  85. SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); sessions.put(owned);
  86. assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
  87. com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver observer = new com.ruoyi.wvp.gb28181.transmit.SIPProcessorObserver();
  88. ReflectionTestUtils.setField(observer, "sessionManager", external.manager());
  89. com.ruoyi.wvp.gb28181.event.SipSubscribe expired = new com.ruoyi.wvp.gb28181.event.SipSubscribe();
  90. expired.addSubscribe("call-141", com.ruoyi.wvp.gb28181.event.sip.SipEvent.getInstance("call-141", result -> fail("expired callback must not execute"), null, -1));
  91. expired.execute(); assertTrue(expired.isEmpty());
  92. ReflectionTestUtils.setField(observer, "sipSubscribe", expired);
  93. javax.sip.Dialog sipDialog = mock(javax.sip.Dialog.class);
  94. doAnswer(i -> { assertTrue(external.manager().isByeConfirmed(owned)); return null; }).when(sipDialog).delete();
  95. observer.processResponse(new javax.sip.ResponseEvent(this, null, sipDialog,
  96. response("BYE", "call-1", 41, "z9hG4bK-wrong", "to-1")));
  97. verify(sipDialog, never()).delete(); assertFalse(sessions.isByeConfirmed(owned));
  98. observer.processResponse(new javax.sip.ResponseEvent(this, null, sipDialog,
  99. response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
  100. verify(sipDialog).delete(); assertTrue(external.manager().isByeConfirmed(owned));
  101. assertNull(external.manager().getSsrcTransactionByStream("rtp", owned.getStream()));
  102. }
  103. @Test void deletionCasCannotEraseAReplacementFromAnotherServiceInstance() throws Exception {
  104. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  105. SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); sessions.put(owned);
  106. assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
  107. assertNotNull(sessions.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
  108. SsrcTransaction replacement = dialog(owned.getStream(), "call-2");
  109. external.beforeCas = () -> external.manager().put(replacement);
  110. assertFalse(sessions.removeManagedIfSame(owned));
  111. assertEquals("call-2", sessions.getSsrcTransactionByStream("rtp", owned.getStream()).getCallId());
  112. assertNotNull(sessions.getSsrcTransactionByCallId("call-1"), "CAS loses both deletes, not only the stream delete");
  113. }
  114. @Test void inviteRetransmitAfterConfirmedByeDoesNotResurrectTheAllocation() throws Exception {
  115. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  116. SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1");
  117. assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
  118. "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
  119. gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
  120. SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
  121. assertTrue(sessions.rememberBye(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"), owned));
  122. assertNotNull(sessions.confirmBye(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1")));
  123. assertTrue(sessions.removeManagedIfSame(owned));
  124. assertNull(external.manager().restoreManagedInvite(actual));
  125. assertNull(external.manager().getSsrcTransactionByStream("rtp", allocation.getStream()));
  126. }
  127. @Test void lateInviteWithoutCallbackAcksMalformedSdpThenStopsOnlyPersistedOriginalSource() throws Exception {
  128. InviteFixture f = new InviteFixture();
  129. gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
  130. actual.setContent("unparseable SDP\r\ny=do-not-associate-by-body", javax.sip.SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
  131. f.processor.process(f.event(actual));
  132. org.mockito.InOrder order = inOrder(f.sender, f.play);
  133. order.verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
  134. order.verify(f.play).stopManaged(f.node, f.device, f.channel, f.stream);
  135. SsrcTransaction persisted = f.external.manager().getSsrcTransactionByStream("rtp", f.stream);
  136. assertNotNull(persisted); assertEquals("to-1", persisted.getSipTransactionInfo().getToTag());
  137. assertEquals("1234567890", persisted.getSsrc());
  138. verify(f.media, never()).getDefaultMediaServer();
  139. verify(f.channels).getOneForSource("device-a", "channel-a");
  140. }
  141. @Test void unrelatedInviteStillGetsLegacyAckButCannotRecoverOrStopAnOwnedStream() throws Exception {
  142. InviteFixture f = new InviteFixture();
  143. f.processor.process(f.event(response("INVITE", "foreign-call", 9, "z9hG4bK-invite", "to-1")));
  144. verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
  145. verifyNoInteractions(f.play, f.media, f.channels, f.devices);
  146. assertNull(f.external.manager().getSsrcTransactionByStream("rtp", f.stream));
  147. }
  148. @Test void retransmittedInviteForAnActiveGenerationOnlyResendsAck() throws Exception {
  149. InviteFixture f = new InviteFixture();
  150. f.generation.setStatus("ACTIVE");
  151. // The original start deadline is old, but healthy playback is not a new start attempt.
  152. f.processor.process(f.event(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
  153. verify(f.sender).transmitRequest(eq("127.0.0.1"), any(javax.sip.message.Message.class));
  154. verifyNoInteractions(f.play);
  155. }
  156. @Test void sourceScopedLookupMismatchRetainsTheDialogWithoutStoppingAnotherSource() throws Exception {
  157. InviteFixture f = new InviteFixture(); f.channel.setId(99);
  158. f.processor.process(f.event(response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1")));
  159. verifyNoInteractions(f.play); assertNotNull(f.external.manager().getSsrcTransactionByStream("rtp", f.stream));
  160. }
  161. @Test void peerByePersistsIndependentTerminationAndFencesInviteRetransmit() throws Exception {
  162. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  163. SSRCInfo allocation = allocation();
  164. assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
  165. "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
  166. gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
  167. SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
  168. assertTrue(sessions.rememberPeerBye(peerBye(owned), owned));
  169. SipInviteSessionManager restarted = external.manager();
  170. assertTrue(restarted.isSipTerminated(owned));
  171. assertFalse(restarted.isByeConfirmed(owned), "peer BYE is not an outgoing BYE response");
  172. assertTrue(restarted.removeManagedIfSame(owned));
  173. assertNull(external.manager().restoreManagedInvite(actual));
  174. assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
  175. }
  176. @Test void malformedForeignAndReplacedPeerRequestsCannotBecomeTerminationEvidence() throws Exception {
  177. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  178. SsrcTransaction owned = dialog("legacy", "call-1");
  179. assertFalse(sessions.rememberPeerBye(peerBye(owned), owned), "unknown dialogs cannot acquire peer evidence");
  180. sessions.put(owned);
  181. gov.nist.javax.sip.message.SIPRequest wrongTags = peerBye(owned);
  182. wrongTags.getFrom().setTag("foreign");
  183. assertFalse(sessions.rememberPeerBye(wrongTags, owned));
  184. gov.nist.javax.sip.message.SIPRequest wrongCall = peerBye(owned);
  185. wrongCall.getCallIdHeader().setCallId("foreign-call");
  186. assertFalse(sessions.rememberPeerBye(wrongCall, owned));
  187. gov.nist.javax.sip.message.SIPRequest wrongCseq = peerBye(owned);
  188. wrongCseq.getCSeqHeader().setMethod("INVITE");
  189. assertFalse(sessions.rememberPeerBye(wrongCseq, owned));
  190. gov.nist.javax.sip.message.SIPRequest noBranch = peerBye(owned);
  191. noBranch.getTopmostViaHeader().removeParameter("branch");
  192. assertFalse(sessions.rememberPeerBye(noBranch, owned));
  193. assertFalse(sessions.rememberPeerBye(request("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1"), owned));
  194. SsrcTransaction replacement = dialog("legacy", "call-1");
  195. replacement.getSipTransactionInfo().setToTag("new-tags");
  196. external.beforeCas = () -> external.manager().put(replacement);
  197. assertFalse(sessions.rememberPeerBye(peerBye(owned), owned));
  198. assertFalse(external.manager().isSipTerminated(owned));
  199. assertFalse(external.manager().isSipTerminated(replacement));
  200. assertFalse(sessions.rememberPeerBye(peerBye(owned), replacement));
  201. assertFalse(sessions.removeIfSame(owned));
  202. assertEquals("new-tags", external.manager().getSsrcTransactionByCallId("call-1").getSipTransactionInfo().getToTag());
  203. }
  204. @Test void snapshotDeleteIsAtomicAcrossBothIndexesWithoutInventingProtocolEvidence() {
  205. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  206. SsrcTransaction owned = dialog("legacy", "call-1"); sessions.put(owned);
  207. SsrcTransaction replacement = dialog("legacy", "call-1");
  208. replacement.getSipTransactionInfo().setToTag("new-tags");
  209. external.beforeCas = () -> external.manager().put(replacement);
  210. assertFalse(sessions.removeIfSame(owned));
  211. assertTrue(SipInviteSessionManager.sameDialog(replacement, external.manager().getSsrcTransactionByCallId("call-1")));
  212. assertTrue(SipInviteSessionManager.sameDialog(replacement, external.manager().getSsrcTransactionByStream("rtp", "legacy")));
  213. assertTrue(external.manager().removeIfSame(replacement));
  214. assertFalse(external.manager().isSipTerminated(replacement), "offline cleanup is not SIP termination");
  215. assertFalse(external.manager().isByeConfirmed(replacement));
  216. }
  217. @Test void peerMarkerArrivingBetweenRestoreReadAndCasCannotResurrectDialog() throws Exception {
  218. RedisBytes external = new RedisBytes(); SipInviteSessionManager sessions = external.manager();
  219. assertTrue(sessions.rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
  220. "node-a", "device-a", 7, "channel-a", allocation(), "127.0.0.1", 1L));
  221. gov.nist.javax.sip.message.SIPResponse actual = response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1");
  222. SsrcTransaction owned = sessions.restoreManagedInvite(actual); assertNotNull(owned);
  223. gov.nist.javax.sip.message.SIPRequest peer = peerBye(owned);
  224. external.beforeCas = () -> {
  225. assertTrue(external.manager().rememberPeerBye(peer, owned));
  226. assertTrue(external.manager().removeIfSame(owned));
  227. };
  228. assertNull(sessions.restoreManagedInvite(actual));
  229. assertTrue(external.manager().isSipTerminated(owned));
  230. assertNull(external.manager().getSsrcTransactionByStream("rtp", owned.getStream()));
  231. }
  232. static gov.nist.javax.sip.message.SIPRequest peerBye(SsrcTransaction owned) throws Exception {
  233. gov.nist.javax.sip.message.SIPRequest peer = (gov.nist.javax.sip.message.SIPRequest)
  234. request("BYE", owned.getCallId(), 77, "z9hG4bK-peer", owned.getSipTransactionInfo().getFromTag());
  235. peer.getFrom().setTag(owned.getSipTransactionInfo().getToTag());
  236. return peer;
  237. }
  238. static class InviteFixture {
  239. final RedisBytes external = new RedisBytes();
  240. final String stream = "managed_11111111111111111111111111111111";
  241. final com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor processor = new com.ruoyi.wvp.gb28181.transmit.event.response.impl.InviteResponseProcessor();
  242. final com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
  243. final com.ruoyi.wvp.gb28181.service.IPlayService play = mock(com.ruoyi.wvp.gb28181.service.IPlayService.class);
  244. final com.ruoyi.wvp.media.service.IMediaServerService media = mock(com.ruoyi.wvp.media.service.IMediaServerService.class);
  245. final com.ruoyi.wvp.gb28181.service.IDeviceChannelService channels = mock(com.ruoyi.wvp.gb28181.service.IDeviceChannelService.class);
  246. final com.ruoyi.wvp.storager.IRedisCatchStorage devices = mock(com.ruoyi.wvp.storager.IRedisCatchStorage.class);
  247. final com.ruoyi.wvp.media.bean.MediaServer node = new com.ruoyi.wvp.media.bean.MediaServer();
  248. final Device device = new Device(); final DeviceChannel channel = new DeviceChannel();
  249. final VideoLifecycleStore lifecycle = mock(VideoLifecycleStore.class);
  250. final VideoLifecycleRecord generation = new VideoLifecycleRecord();
  251. InviteFixture() throws Exception {
  252. generation.setGeneration("11111111-1111-1111-1111-111111111111");
  253. generation.setStatus("STARTING"); generation.setDeadline(1L);
  254. when(lifecycle.find(generation.getGeneration())).thenReturn(generation);
  255. SSRCInfo allocation = new SSRCInfo(30000, "1234567890", "rtp", stream, "timeout-1");
  256. assertTrue(external.manager().rememberInvite(request("INVITE", "call-1", 9, "z9hG4bK-invite", null),
  257. "node-a", "device-a", 7, "channel-a", allocation, "127.0.0.1", 1L));
  258. node.setId("node-a"); device.setDeviceId("device-a"); channel.setId(7); channel.setDeviceId("channel-a");
  259. when(media.getOne("node-a")).thenReturn(node); when(devices.getDevice("device-a")).thenReturn(device);
  260. when(channels.getOneForSource("device-a", "channel-a")).thenReturn(channel);
  261. com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
  262. when(headers.createAckRequest(anyString(), any(), any())).thenReturn(request("ACK", "call-1", 9, "z9hG4bK-ack", "to-1"));
  263. ReflectionTestUtils.setField(processor, "sessionManager", external.manager());
  264. ReflectionTestUtils.setField(processor, "sipSender", sender); ReflectionTestUtils.setField(processor, "headerProvider", headers);
  265. ReflectionTestUtils.setField(processor, "playService", play); ReflectionTestUtils.setField(processor, "mediaServerService", media);
  266. ReflectionTestUtils.setField(processor, "redisCatchStorage", devices); ReflectionTestUtils.setField(processor, "deviceChannelService", channels);
  267. ReflectionTestUtils.setField(processor, "videoLifecycleStore", lifecycle);
  268. }
  269. gov.nist.javax.sip.ResponseEventExt event(gov.nist.javax.sip.message.SIPResponse response) throws Exception {
  270. gov.nist.javax.sip.message.SIPResponse received = spy(response);
  271. when(received.getLocalAddress()).thenReturn(java.net.InetAddress.getByName("127.0.0.1"));
  272. gov.nist.javax.sip.ResponseEventExt event = mock(gov.nist.javax.sip.ResponseEventExt.class);
  273. when(event.getResponse()).thenReturn(received); when(event.getRemoteIpAddress()).thenReturn("127.0.0.2"); when(event.getRemotePort()).thenReturn(5060);
  274. return event;
  275. }
  276. }
  277. @Test void commanderPersistsBeforeInviteSendAndOriginalCallbackAcceptsOnlyBoundResponse() throws Exception {
  278. RedisBytes external = new RedisBytes();
  279. com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
  280. com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
  281. java.util.concurrent.atomic.AtomicReference<com.ruoyi.wvp.gb28181.event.SipSubscribe.Event> callback = new java.util.concurrent.atomic.AtomicReference<>();
  282. doAnswer(i -> {
  283. assertNotNull(external.manager().getPendingInviteByStream("rtp", "managed_11111111111111111111111111111111"));
  284. callback.set(i.getArgument(3)); return null;
  285. }).when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any(), anyLong());
  286. java.util.concurrent.atomic.AtomicInteger published = new java.util.concurrent.atomic.AtomicInteger();
  287. commander.playStreamCmd(node(), allocation(), device(), channel(), result -> published.incrementAndGet(), result -> { }, 60000L);
  288. callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
  289. response("INVITE", "call-1", 9, "z9hG4bK-wrong", "to-1"))));
  290. assertEquals(0, published.get()); assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
  291. callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
  292. response("INVITE", "call-1", 9, "z9hG4bK-invite", "to-1"))));
  293. assertEquals(1, published.get()); assertNotNull(external.manager().getSsrcTransactionByCallId("call-1"));
  294. }
  295. @Test void commanderNeverSendsInviteWhenPreDispatchPersistenceFails() throws Exception {
  296. RedisBytes external = new RedisBytes(); external.rejectCas = true;
  297. com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
  298. com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
  299. assertThrows(javax.sip.SipException.class, () -> commander.playStreamCmd(node(), allocation(), device(), channel(), result -> { }, result -> { }, 60000L));
  300. verify(sender, never()).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any(), anyLong());
  301. }
  302. @Test void commanderByeCallbackPersistsConfirmationBeforeNotifyingCaller() throws Exception {
  303. RedisBytes external = new RedisBytes(); SsrcTransaction owned = dialog("managed_11111111111111111111111111111111", "call-1"); external.manager().put(owned);
  304. com.ruoyi.wvp.gb28181.transmit.SIPSender sender = mock(com.ruoyi.wvp.gb28181.transmit.SIPSender.class);
  305. com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = commander(external, sender);
  306. java.util.concurrent.atomic.AtomicReference<com.ruoyi.wvp.gb28181.event.SipSubscribe.Event> callback = new java.util.concurrent.atomic.AtomicReference<>();
  307. doAnswer(i -> { assertTrue(external.manager().hasByeRequest(response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"))); callback.set(i.getArgument(3)); return null; })
  308. .when(sender).transmitRequest(anyString(), any(javax.sip.message.Message.class), any(), any());
  309. java.util.concurrent.atomic.AtomicInteger notified = new java.util.concurrent.atomic.AtomicInteger();
  310. commander.streamByeCmd(device(), "channel-a", "rtp", owned.getStream(), "call-1", result -> {
  311. assertTrue(external.manager().isByeConfirmed(owned)); notified.incrementAndGet();
  312. });
  313. assertFalse(external.manager().isByeConfirmed(owned));
  314. callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
  315. response("INVITE", "call-1", 41, "z9hG4bK-bye", "to-1"))));
  316. assertEquals(0, notified.get());
  317. callback.get().response(new com.ruoyi.wvp.gb28181.event.SipSubscribe.EventResult<>(new javax.sip.ResponseEvent(this, null, null,
  318. response("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"))));
  319. assertEquals(1, notified.get()); assertNull(external.manager().getSsrcTransactionByCallId("call-1"));
  320. }
  321. static com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander(RedisBytes external, com.ruoyi.wvp.gb28181.transmit.SIPSender sender) throws Exception {
  322. com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander commander = new com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander();
  323. com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider headers = mock(com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider.class);
  324. when(headers.createInviteRequest(any(), anyString(), anyString(), anyString(), anyString(), isNull(), anyString(), any()))
  325. .thenReturn(request("INVITE", "call-1", 9, "z9hG4bK-invite", null));
  326. when(headers.createByteRequest(any(), anyString(), any())).thenReturn(request("BYE", "call-1", 41, "z9hG4bK-bye", "to-1"));
  327. com.ruoyi.wvp.gb28181.SipLayer layer = mock(com.ruoyi.wvp.gb28181.SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
  328. UserSetting settings = new UserSetting(); settings.setSeniorSdp(false);
  329. ReflectionTestUtils.setField(commander, "sessionManager", external.manager()); ReflectionTestUtils.setField(commander, "sipSender", sender);
  330. ReflectionTestUtils.setField(commander, "headerProvider", headers); ReflectionTestUtils.setField(commander, "sipLayer", layer);
  331. ReflectionTestUtils.setField(commander, "videoLifecycleStore", mock(VideoLifecycleStore.class)); ReflectionTestUtils.setField(commander, "userSetting", settings);
  332. return commander;
  333. }
  334. static Device device() { Device d = new Device(); d.setDeviceId("device-a"); d.setStreamMode("UDP"); return d; }
  335. static DeviceChannel channel() { DeviceChannel c = new DeviceChannel(); c.setId(7); c.setDeviceId("channel-a"); return c; }
  336. 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; }
  337. static SSRCInfo allocation() { return new SSRCInfo(30000, "1234567890", "rtp", "managed_11111111111111111111111111111111", "timeout-1"); }
  338. static javax.sip.message.Request request(String method, String call, long seq, String branch, String toTag) throws Exception {
  339. return javax.sip.SipFactory.getInstance().createMessageFactory().createRequest(
  340. method + " sip:channel@127.0.0.2:5060 SIP/2.0\r\n" + headers(method, call, seq, branch, toTag));
  341. }
  342. static gov.nist.javax.sip.message.SIPResponse response(String method, String call, long seq, String branch, String toTag) throws Exception {
  343. return (gov.nist.javax.sip.message.SIPResponse) javax.sip.SipFactory.getInstance().createMessageFactory()
  344. .createResponse("SIP/2.0 200 OK\r\n" + headers(method, call, seq, branch, toTag));
  345. }
  346. static String headers(String method, String call, long seq, String branch, String toTag) {
  347. return "Via: SIP/2.0/UDP 127.0.0.1:5060;branch=" + branch + "\r\n"
  348. + "From: <sip:server@127.0.0.1>;tag=from-1\r\nTo: <sip:channel@127.0.0.2>" + (toTag == null ? "" : ";tag=" + toTag)
  349. + "\r\nCall-ID: " + call + "\r\nCSeq: " + seq + " " + method + "\r\nMax-Forwards: 70\r\nContent-Length: 0\r\n\r\n";
  350. }
  351. static SsrcTransaction dialog(String stream, String call) {
  352. SsrcTransaction tx = new SsrcTransaction();
  353. tx.setDeviceId("device-a"); tx.setChannelId(7); tx.setApp("rtp"); tx.setStream(stream);
  354. tx.setMediaServerId("node-a"); tx.setSsrc("1234567890"); tx.setCallId(call); tx.setType(InviteSessionType.PLAY);
  355. SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(call); sip.setFromTag("from-1");
  356. sip.setToTag("to-1"); sip.setViaBranch("z9hG4bK-invite"); tx.setSipTransactionInfo(sip); return tx;
  357. }
  358. static class RedisBytes {
  359. final Map<String, Map<String, byte[]>> data = new HashMap<>();
  360. final StringRedisSerializer strings = new StringRedisSerializer();
  361. final GenericJackson2JsonRedisSerializer values = new GenericJackson2JsonRedisSerializer();
  362. Runnable beforeCas;
  363. boolean rejectCas;
  364. @SuppressWarnings({"unchecked", "rawtypes"})
  365. RedisTemplate<Object,Object> client() {
  366. RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
  367. HashOperations<Object,Object,Object> hashes = mock(HashOperations.class);
  368. when(redis.opsForHash()).thenReturn(hashes);
  369. when(redis.getKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
  370. when(redis.getHashKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
  371. doReturn(values).when(redis).getHashValueSerializer();
  372. doAnswer(i -> { put(i.getArgument(0).toString(), i.getArgument(1).toString(), values.serialize(i.getArgument(2))); return null; })
  373. .when(hashes).put(any(), any(), any());
  374. when(hashes.get(any(), any())).thenAnswer(i -> values.deserialize(get(i.getArgument(0).toString(), i.getArgument(1).toString())));
  375. when(hashes.values(any())).thenAnswer(i -> {
  376. List<Object> result = new ArrayList<>();
  377. for (byte[] bytes : data.getOrDefault(i.getArgument(0).toString(), Collections.emptyMap()).values()) result.add(values.deserialize(bytes));
  378. return result;
  379. });
  380. when(hashes.delete(any(), any())).thenAnswer(i -> data.getOrDefault(i.getArgument(0).toString(), Collections.emptyMap()).remove(i.getArgument(1).toString()) == null ? 0L : 1L);
  381. RedisConnection connection = mock(RedisConnection.class);
  382. when(redis.execute(any(RedisCallback.class))).thenAnswer(i -> ((RedisCallback<?>) i.getArgument(0)).doInRedis(connection));
  383. when(connection.eval(any(byte[].class), eq(ReturnType.INTEGER), anyInt(), org.mockito.ArgumentMatchers.<byte[][]>any())).thenAnswer(i -> {
  384. if (rejectCas) return 0L;
  385. if (beforeCas != null) { Runnable race = beforeCas; beforeCas = null; race.run(); }
  386. int n = i.getArgument(2);
  387. Object[] invocation = i.getArguments();
  388. byte[][] args = invocation.length == 4 && invocation[3] instanceof byte[][]
  389. ? (byte[][]) invocation[3] : Arrays.copyOfRange(invocation, 3, invocation.length, byte[][].class);
  390. // Emulate the generic compare-all-then-write-all Lua at the external Redis boundary.
  391. synchronized (data) {
  392. for (int k = 0; k < n; k++) {
  393. int a = n + k * 5;
  394. byte[] expected = "1".equals(text(args[a+1])) ? args[a+2] : null;
  395. if (!Arrays.equals(expected, get(text(args[k]), text(args[a])))) return 0L;
  396. }
  397. for (int k = 0; k < n; k++) {
  398. int a = n + k * 5;
  399. if ("1".equals(text(args[a+3]))) put(text(args[k]), text(args[a]), args[a+4]);
  400. else data.computeIfAbsent(text(args[k]), unused -> new HashMap<>()).remove(text(args[a]));
  401. }
  402. return 1L;
  403. }
  404. });
  405. return redis;
  406. }
  407. SipInviteSessionManager manager() {
  408. SipInviteSessionManager result = new SipInviteSessionManager();
  409. UserSetting settings = new UserSetting(); settings.setServerId("late-test");
  410. ReflectionTestUtils.setField(result, "userSetting", settings);
  411. ReflectionTestUtils.setField(result, "redisTemplate", client()); return result;
  412. }
  413. byte[] get(String key, String field) { byte[] bytes = data.getOrDefault(key, Collections.emptyMap()).get(field); return bytes == null ? null : bytes.clone(); }
  414. void put(String key, String field, byte[] bytes) { data.computeIfAbsent(key, unused -> new HashMap<>()).put(field, bytes.clone()); }
  415. static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
  416. }
  417. }