VideoStopReceiptRestartTest.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. package com.zksy.video.lifecycle;
  2. import com.alibaba.fastjson2.JSONObject;
  3. import com.ruoyi.wvp.common.*;
  4. import com.ruoyi.wvp.common.InviteInfo;
  5. import com.ruoyi.wvp.conf.*;
  6. import com.ruoyi.wvp.gb28181.SipLayer;
  7. import com.ruoyi.wvp.gb28181.bean.*;
  8. import com.ruoyi.wvp.gb28181.event.SipSubscribe;
  9. import com.ruoyi.wvp.gb28181.service.impl.*;
  10. import com.ruoyi.wvp.gb28181.session.*;
  11. import com.ruoyi.wvp.gb28181.transmit.*;
  12. import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
  13. import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
  14. import com.ruoyi.wvp.mapper.*;
  15. import com.ruoyi.wvp.media.bean.MediaServer;
  16. import com.ruoyi.wvp.media.event.hook.HookSubscribe;
  17. import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
  18. import com.ruoyi.wvp.media.zlm.*;
  19. import com.ruoyi.wvp.service.bean.*;
  20. import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
  21. import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
  22. import com.ruoyi.wvp.utils.redis.FastJsonRedisSerializer;
  23. import gov.nist.javax.sip.message.SIPResponse;
  24. import org.junit.jupiter.api.Test;
  25. import org.springframework.data.redis.connection.*;
  26. import org.springframework.data.redis.core.*;
  27. import org.springframework.data.redis.serializer.StringRedisSerializer;
  28. import org.springframework.test.util.ReflectionTestUtils;
  29. import javax.sip.*;
  30. import javax.sip.header.*;
  31. import javax.sip.message.Request;
  32. import java.nio.charset.StandardCharsets;
  33. import java.util.*;
  34. import java.util.concurrent.atomic.AtomicInteger;
  35. import java.util.function.Predicate;
  36. import static org.junit.jupiter.api.Assertions.*;
  37. import static org.mockito.ArgumentMatchers.*;
  38. import static org.mockito.Mockito.*;
  39. /** Real Play/RTP/Hook/Invite/Session/Commander/header/media modules; only I/O and timer are substituted. */
  40. class VideoStopReceiptRestartTest {
  41. private static final String STREAM = "managed_11111111111111111111111111111111";
  42. private static final String LEGACY = "device_channel";
  43. @Test void positiveRtpReceiptSurvivesRebuildingBothRtpAndReceiptModule() throws Exception {
  44. External world = new External(); Instance first = new Instance(world);
  45. SSRCInfo allocation = first.open(STREAM); assertNotNull(allocation);
  46. assertTrue(first.rtp.closeManagedRTPServer(world.node, allocation));
  47. Instance second = new Instance(world);
  48. assertTrue(second.rtp.closeManagedRTPServer(world.node, allocation));
  49. assertEquals(1, world.closeRequests.size());
  50. assertNull(second.open(STREAM));
  51. }
  52. @Test void rebuiltRtpReturnsItsOriginalSsrcWithoutReturningAReusedNumberAgain() throws Exception {
  53. External world = new External();
  54. String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
  55. world.ssrcRedis.strings().delete(pool);
  56. world.ssrcRedis.strings().opsForSet().add(pool, "200000001");
  57. SSRCInfo original = new Instance(world).open(STREAM);
  58. assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
  59. assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, original));
  60. assertEquals(1L, world.ssrcRedis.strings().opsForSet().size(pool));
  61. SSRCInfo another = new Instance(world).open("other_legacy_stream");
  62. assertNotNull(another); assertEquals(original.getSsrc(), another.getSsrc());
  63. assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
  64. assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, original));
  65. assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool), "a duplicate close never makes an occupied number available");
  66. assertTrue(world.open.contains("other_legacy_stream"));
  67. }
  68. @Test void negotiatedSsrcKeepsTheOriginalPoolNumberForCloseAndReturn() throws Exception {
  69. External world = new External();
  70. Instance instance = new Instance(world);
  71. String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
  72. world.ssrcRedis.strings().delete(pool);
  73. world.ssrcRedis.strings().opsForSet().add(pool, "200000001");
  74. SSRCInfo original = instance.open(STREAM);
  75. // The device renegotiates a different SSRC while the original pool number stays owned.
  76. String negotiated = "0999999999";
  77. assertTrue(instance.receipts.recordNegotiatedSsrc(world.node.getId(), STREAM, original, negotiated, false));
  78. SSRCInfo current = new SSRCInfo(original.getPort(), negotiated, "rtp", STREAM, original.getTimeOutTaskKey());
  79. assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, current));
  80. assertEquals(1L, world.ssrcRedis.strings().opsForSet().size(pool), "the original pool number is returned once");
  81. // The next allocation proves which number came back: the original, never the negotiated one.
  82. assertEquals(original.getSsrc(), new Instance(world).open("next_stream").getSsrc());
  83. assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
  84. }
  85. @Test void delayedLegacyCloseReturnsSsrcWhenTheCallerNeverRetries() throws Exception {
  86. External world = new External(); world.delayClose = true;
  87. Instance instance = new Instance(world);
  88. SSRCInfo allocation = instance.open(LEGACY);
  89. String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
  90. assertEquals(99L, world.ssrcRedis.strings().opsForSet().size(pool));
  91. instance.rtp.closeRTPServer(world.node, allocation);
  92. assertEquals(99L, world.ssrcRedis.strings().opsForSet().size(pool));
  93. world.closeReplies.get(0).run();
  94. assertEquals(100L, world.ssrcRedis.strings().opsForSet().size(pool), "the positive async receipt must finish pool cleanup without a second stop call");
  95. assertEquals(1, world.closeRequests.size());
  96. }
  97. @Test void managedStopRecoversOriginalDialogAfterByeReceiptAndLiveDialogDeletion() throws Exception {
  98. External world = new External(); Instance first = new Instance(world);
  99. first.managed();
  100. assertFalse(first.stopManaged());
  101. assertTrue(first.hooks.getAll().isEmpty());
  102. Request bye = world.lastBye();
  103. // Fresh observer has no SipSubscribe callbacks. Only serialized Redis state survives.
  104. Instance second = new Instance(world); second.response(bye, 200);
  105. assertNull(second.sessions.getSsrcTransactionByStream("rtp", STREAM));
  106. assertTrue(second.stopManaged());
  107. assertTrue(new Instance(world).stopManaged());
  108. assertEquals(1, world.closeRequests.size());
  109. }
  110. @Test void successfulSendAndRtpCloseWithoutBye2xxStayPendingAfterRestart() throws Exception {
  111. External world = new External(); Instance first = new Instance(world); first.managed();
  112. assertFalse(first.stopManaged());
  113. Instance second = new Instance(world);
  114. assertFalse(second.stopManaged());
  115. second.response(world.lastBye(), 500);
  116. assertFalse(new Instance(world).stopManaged());
  117. assertEquals(1, world.closeRequests.size());
  118. }
  119. @Test void adoptedStopRecoversAndOldHandleCannotCloseSameNameReplacement() throws Exception {
  120. External world = new External(); Instance first = new Instance(world);
  121. SSRCInfo original = first.legacy("call-old"); String handle = first.adopt(); assertNotNull(handle);
  122. assertFalse(first.stopAdopted(handle)); Request bye = world.lastBye();
  123. Instance second = new Instance(world); second.response(bye, 200);
  124. assertTrue(second.stopAdopted(handle));
  125. SSRCInfo replacement = second.legacy("call-new");
  126. assertNotEquals(original.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
  127. Instance third = new Instance(world);
  128. assertFalse(third.stopAdopted(handle));
  129. assertFalse(third.rtp.closeAdoptedRTPServer(world.node, original, "call-old"));
  130. third.rtp.closeRTPServer(world.node, original); // a late ordinary timeout uses the same allocation fence
  131. assertEquals(1, world.closeRequests.size());
  132. assertTrue(world.open.contains(LEGACY));
  133. assertEquals("call-new", third.sessions.getSsrcTransactionByStream("rtp", LEGACY).getCallId());
  134. }
  135. @Test void unknownNameCloseIsNotRepeatedAndCannotReopenEvenAfterBye2xxAndRestart() throws Exception {
  136. External world = new External(); world.delayClose = true;
  137. Instance first = new Instance(world); first.legacy("call-old"); String handle = first.adopt();
  138. assertFalse(first.stopAdopted(handle));
  139. Instance second = new Instance(world); second.response(world.lastBye(), 200);
  140. assertFalse(second.stopAdopted(handle)); assertNull(second.open(LEGACY));
  141. assertEquals(1, world.closeRequests.size()); assertEquals(1, world.openRequests.get());
  142. world.closeReplies.get(0).run();
  143. assertTrue(new Instance(world).stopAdopted(handle));
  144. }
  145. @Test void hitZeroAndNonzeroCodeAreNotDurableCloseEvidence() throws Exception {
  146. for (String reply : List.of("{\"code\":0,\"hit\":0}", "{\"code\":-1,\"hit\":1}")) {
  147. External world = new External(); world.closeReply = reply;
  148. Instance first = new Instance(world); first.managed(); assertFalse(first.stopManaged());
  149. Instance second = new Instance(world); second.response(world.lastBye(), 200);
  150. assertFalse(second.stopManaged()); assertFalse(new Instance(world).stopManaged());
  151. assertEquals(1, world.closeRequests.size());
  152. }
  153. }
  154. @Test void positiveCallbackWithFailedReceiptWriteCannotBeMaskedByLocalSuccess() throws Exception {
  155. External world = new External(); Instance first = new Instance(world); first.managed();
  156. world.redis.failWrite = value -> value.contains("\"state\":\"CLOSED\"");
  157. assertFalse(first.stopManaged());
  158. world.redis.failWrite = value -> false;
  159. first.response(world.lastBye(), 200);
  160. assertFalse(first.stopManaged()); assertFalse(new Instance(world).stopManaged());
  161. assertEquals(1, world.closeRequests.size());
  162. }
  163. @Test void failedIntentWriteNeverDispatchesCreateAndMissingReceiptIsNotStopped() throws Exception {
  164. External world = new External(); Instance first = new Instance(world);
  165. world.redis.failWrite = value -> true;
  166. assertThrows(RuntimeException.class, () -> first.play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { }));
  167. world.redis.failWrite = value -> false;
  168. assertFalse(new Instance(world).stopManaged());
  169. assertEquals(0, world.openRequests.get()); assertTrue(world.requests.isEmpty());
  170. }
  171. @Test void closeCompareAndSetLoserCannotDispatchASecondNameClose() throws Exception {
  172. External world = new External(); Instance first = new Instance(world), second = new Instance(world);
  173. SSRCInfo allocation = first.open(STREAM);
  174. world.redis.beforeExec = () -> assertTrue(second.rtp.closeManagedRTPServer(world.node, allocation));
  175. assertFalse(first.rtp.closeManagedRTPServer(world.node, allocation));
  176. assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, allocation));
  177. assertEquals(1, world.closeRequests.size());
  178. }
  179. @Test void managedUuidCannotBeReallocatedOnAnotherNodeAfterReconstruction() throws Exception {
  180. External world = new External(); Instance first = new Instance(world);
  181. SSRCInfo allocation = first.open(STREAM); assertTrue(first.rtp.closeManagedRTPServer(world.node, allocation));
  182. MediaServer other = new MediaServer(); other.setId("node-b"); other.setType("zlm"); other.setRtpEnable(true);
  183. RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(other); param.setStreamId(STREAM);
  184. Instance second = new Instance(world);
  185. assertNull(second.rtp.openRTPServer(param, (c, m, r) -> { }));
  186. assertFalse(second.rtp.closeManagedRTPServer(other, allocation));
  187. assertEquals(1, world.openRequests.get()); assertEquals(1, world.closeRequests.size());
  188. }
  189. @Test void oldConfirmationCannotAuthorizeChangedTagsEvenIfCallIdAndSsrcWereReused() throws Exception {
  190. External world = new External(); Instance first = new Instance(world);
  191. first.legacy("reused-call"); String handle = first.adopt(); assertFalse(first.stopAdopted(handle));
  192. Request oldBye = world.lastBye();
  193. Instance second = new Instance(world);
  194. SsrcTransaction replacement = second.sessions.getSsrcTransactionByStream("rtp", LEGACY);
  195. replacement.getSipTransactionInfo().setToTag("new-dialog-tag"); second.sessions.put(replacement);
  196. second.response(oldBye, 200);
  197. Instance third = new Instance(world);
  198. assertFalse(third.stopAdopted(handle));
  199. assertEquals("new-dialog-tag", third.sessions.getSsrcTransactionByStream("rtp", LEGACY).getSipTransactionInfo().getToTag());
  200. assertEquals(1, world.closeRequests.size());
  201. }
  202. @Test void lostCreateResultRemainsCreatingAcrossRestartWithoutCloseOrReopen() throws Exception {
  203. External world = new External(); world.throwDuringOpen = true;
  204. Instance first = new Instance(world); assertNull(first.open(STREAM));
  205. Instance second = new Instance(world);
  206. assertNull(second.open(STREAM));
  207. assertTrue(world.closeRequests.isEmpty()); assertEquals(1, world.openRequests.get());
  208. }
  209. static class Instance {
  210. final PlayServiceImpl play = new PlayServiceImpl();
  211. final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
  212. final HookSubscribe hooks = new HookSubscribe();
  213. final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
  214. final SipInviteSessionManager sessions = new SipInviteSessionManager();
  215. final SIPProcessorObserver observer = new SIPProcessorObserver();
  216. final SIPCommander commander = new SIPCommander();
  217. final External world;
  218. final VideoStopReceipts receipts;
  219. Instance(External world) throws Exception {
  220. this.world = world;
  221. UserSetting settings = new UserSetting(); settings.setServerId("restart-test"); settings.setPlayTimeout(30000);
  222. RedisTemplate<Object,Object> redis = world.redis.client();
  223. StringRedisTemplate strings = world.redis.strings();
  224. receipts = new VideoStopReceipts(redis);
  225. RedisVideoLifecycleStore lifecycle = new RedisVideoLifecycleStore(strings);
  226. SSRCFactory ssrc = new SSRCFactory(); wire(ssrc, "redisTemplate", world.ssrcRedis.strings()); wire(ssrc, "userSetting", settings);
  227. wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
  228. wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
  229. RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
  230. wire(cache, "redisTemplate", redis); wire(cache, "userSetting", settings); cache.updateDevice(world.device);
  231. DeviceMapper devices = mock(DeviceMapper.class); DeviceChannelMapper channels = mock(DeviceChannelMapper.class);
  232. when(devices.getDeviceByDeviceId("device")).thenReturn(world.device);
  233. when(channels.getOneByDeviceIdForSource(1, "channel")).thenReturn(world.channel);
  234. DeviceChannelServiceImpl channelService = new DeviceChannelServiceImpl();
  235. wire(channelService, "deviceMapper", devices); wire(channelService, "channelMapper", channels);
  236. ZLMServerFactory zlm = new ZLMServerFactory(); wire(zlm, "zlmresTfulUtils", world.zlm);
  237. ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService(); wire(zlmNode, "zlmServerFactory", zlm);
  238. MediaServerServiceImpl media = new MediaServerServiceImpl(); wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode));
  239. wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class));
  240. wire(rtp, "ssrcFactory", ssrc); wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks);
  241. wire(rtp, "sessionManager", sessions); wire(rtp, "videoLifecycleStore", lifecycle); wire(rtp, "stopReceipts", receipts);
  242. SipConfig sipConfig = new SipConfig(); sipConfig.setId("34020000002000000001"); sipConfig.setDomain("3402000000"); sipConfig.setPort(5060);
  243. SipLayer layer = mock(SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
  244. SIPRequestHeaderProvider headers = new SIPRequestHeaderProvider();
  245. wire(headers, "sipConfig", sipConfig); wire(headers, "sipLayer", layer); wire(headers, "redisCatchStorage", cache);
  246. wire(commander, "headerProvider", headers); wire(commander, "sessionManager", sessions);
  247. wire(commander, "sipSender", world.sender); wire(commander, "sipLayer", layer);
  248. wire(commander, "sipConfig", sipConfig); wire(commander, "userSetting", settings); wire(commander, "videoLifecycleStore", lifecycle);
  249. wire(observer, "sessionManager", sessions); wire(observer, "sipSubscribe", new SipSubscribe());
  250. wire(play, "cmder", commander); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channelService);
  251. wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
  252. wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media);
  253. wire(play, "videoLifecycleStore", lifecycle); wire(play, "userSetting", settings); wire(play, "stopReceipts", receipts);
  254. }
  255. SSRCInfo open(String stream) {
  256. RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(world.node); param.setStreamId(stream);
  257. return rtp.openRTPServer(param, (code, msg, result) -> { });
  258. }
  259. void managed() throws Exception {
  260. SSRCInfo info = play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { }); assertNotNull(info);
  261. Request invite = world.requests.get(world.requests.size() - 1); assertEquals(Request.INVITE, invite.getMethod());
  262. SIPResponse reply = reply(invite, 200);
  263. reply.setContent("v=0\r\ns=Play\r\ny=" + info.getSsrc() + "\r\n",
  264. SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
  265. world.inviteCallbacks.get(invite).response(new SipSubscribe.EventResult<>(new ResponseEvent(this, null, null, reply)));
  266. assertNotNull(sessions.getSsrcTransactionByStream("rtp", STREAM));
  267. }
  268. SSRCInfo legacy(String call) {
  269. SSRCInfo info = open(LEGACY); assertNotNull(info);
  270. invites.updateInviteInfo(InviteInfo.getInviteInfo("device", 7, LEGACY, info, "node-a", "127.0.0.1", 30000,
  271. "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false));
  272. SsrcTransaction tx = new SsrcTransaction(); tx.setApp("rtp"); tx.setStream(LEGACY); tx.setDeviceId("device");
  273. tx.setChannelId(7); tx.setMediaServerId("node-a"); tx.setSsrc(info.getSsrc()); tx.setCallId(call); tx.setType(InviteSessionType.PLAY);
  274. SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(call); sip.setFromTag("from-old");
  275. sip.setToTag("to-old"); sip.setViaBranch("z9hG4bK-old"); tx.setSipTransactionInfo(sip); sessions.put(tx); return info;
  276. }
  277. String adopt() { return play.adoptStream(world.node, world.device, world.channel, LEGACY, null); }
  278. boolean stopAdopted(String handle) { return play.stopAdopted(world.node, world.device, world.channel, LEGACY, handle); }
  279. boolean stopManaged() { return play.stopManaged(world.node, world.device, world.channel, STREAM); }
  280. void response(Request request, int status) throws Exception { observer.processResponse(new ResponseEvent(this, null, null, reply(request, status))); }
  281. }
  282. static SIPResponse reply(Request request, int status) throws Exception {
  283. SIPResponse reply = (SIPResponse) SipFactory.getInstance().createMessageFactory().createResponse(status, request);
  284. if (reply.getToTag() == null) reply.getTo().setTag("to-managed");
  285. return reply;
  286. }
  287. static class External {
  288. final RedisMemory redis = new RedisMemory();
  289. final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
  290. final SIPSender sender = mock(SIPSender.class);
  291. final MediaServer node = new MediaServer(); final Device device = new Device(); final DeviceChannel channel = new DeviceChannel();
  292. final Set<String> open = new HashSet<>(); final List<String> closeRequests = new ArrayList<>();
  293. final List<Runnable> closeReplies = new ArrayList<>(); final List<Request> requests = new ArrayList<>();
  294. final Map<Request, SipSubscribe.Event> inviteCallbacks = new IdentityHashMap<>();
  295. final AtomicInteger openRequests = new AtomicInteger(), calls = new AtomicInteger();
  296. boolean delayClose, throwDuringOpen;
  297. String closeReply = "{\"code\":0,\"hit\":1}";
  298. final FakeStringRedis ssrcRedis = new FakeStringRedis();
  299. External() throws Exception {
  300. for (int i = 1; i <= 100; i++) ssrcRedis.strings().opsForSet().add(
  301. "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a", String.format("20000%04d", i));
  302. node.setId("node-a"); node.setType("zlm"); node.setRtpEnable(true); node.setSdpIp("127.0.0.1");
  303. device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP"); device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
  304. channel.setId(7); channel.setDeviceId("channel");
  305. when(zlm.getRtpInfo(any(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":0,\"exist\":false}"));
  306. when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
  307. openRequests.incrementAndGet(); open.add((String) ((Map<?,?>) i.getArgument(1)).get("stream_id"));
  308. if (throwDuringOpen) throw new IllegalStateException("response lost after dispatch");
  309. return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
  310. });
  311. doAnswer(i -> {
  312. String stream = (String) ((Map<?,?>) i.getArgument(1)).get("stream_id"); closeRequests.add(stream);
  313. ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
  314. Runnable reply = () -> {
  315. JSONObject result = JSONObject.parseObject(closeReply);
  316. if (Integer.valueOf(0).equals(result.getInteger("code")) && Integer.valueOf(1).equals(result.getInteger("hit"))) open.remove(stream);
  317. callback.run(result);
  318. };
  319. closeReplies.add(reply); if (!delayClose) reply.run(); return null;
  320. }).when(zlm).closeRtpServer(any(), anyMap(), any());
  321. when(sender.getNewCallIdHeader(anyString(), anyString())).thenAnswer(i -> SipFactory.getInstance().createHeaderFactory().createCallIdHeader("call-" + calls.incrementAndGet()));
  322. doAnswer(i -> { requests.add(i.getArgument(1)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
  323. doAnswer(i -> { Request request = i.getArgument(1); requests.add(request); inviteCallbacks.put(request, i.getArgument(3)); return null; })
  324. .when(sender).transmitRequest(any(), any(), any(), any(), anyLong());
  325. }
  326. Request lastBye() { return requests.stream().filter(r -> Request.BYE.equals(r.getMethod())).reduce((a, b) -> b).orElseThrow(); }
  327. }
  328. static void wire(Object target, String field, Object dependency) {
  329. ReflectionTestUtils.setField(target, field, dependency); // dependency injection only, never business state
  330. }
  331. /** Serialized external Redis substitute, including WATCH conflicts and all-or-nothing SIP hash CAS. */
  332. static class RedisMemory {
  333. final Map<String, byte[]> values = new HashMap<>();
  334. final Map<String, Map<String, byte[]>> hashes = new HashMap<>();
  335. final Map<String, Long> versions = new HashMap<>();
  336. final FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
  337. final StringRedisSerializer strings = new StringRedisSerializer();
  338. final AtomicInteger ssrc = new AtomicInteger(1), sequence = new AtomicInteger();
  339. Predicate<String> failWrite = value -> false;
  340. Runnable beforeExec;
  341. @SuppressWarnings({"unchecked", "rawtypes"})
  342. RedisTemplate<Object,Object> client() {
  343. RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
  344. ValueOperations<Object,Object> vals = mock(ValueOperations.class); HashOperations<Object,Object,Object> hash = mock(HashOperations.class);
  345. when(redis.opsForValue()).thenReturn(vals); when(redis.opsForHash()).thenReturn(hash);
  346. when(redis.getKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
  347. when(redis.getHashKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
  348. doReturn(serializer).when(redis).getHashValueSerializer();
  349. Map<String,Long> watched = new HashMap<>(); List<Runnable> queued = new ArrayList<>(); boolean[] multi = { false };
  350. doAnswer(i -> { String key = i.getArgument(0).toString(); watched.put(key, versions.getOrDefault(key, 0L)); return null; }).when(redis).watch(any(Object.class));
  351. doAnswer(i -> { multi[0] = true; return null; }).when(redis).multi();
  352. doAnswer(i -> { multi[0] = false; queued.clear(); watched.clear(); return null; }).when(redis).discard();
  353. doAnswer(i -> { watched.clear(); return null; }).when(redis).unwatch();
  354. when(vals.get(any())).thenAnswer(i -> serializer.deserialize(values.get(i.getArgument(0).toString())));
  355. when(vals.increment(any(), anyLong())).thenAnswer(i -> (long) sequence.incrementAndGet());
  356. doAnswer(i -> {
  357. String key = i.getArgument(0).toString(); Object value = i.getArgument(1); byte[] encoded = serializer.serialize(value);
  358. Runnable write = () -> {
  359. if (failWrite.test(value.toString())) throw new IllegalStateException("Redis write unavailable");
  360. values.put(key, encoded); versions.merge(key, 1L, Long::sum);
  361. };
  362. if (multi[0]) queued.add(write); else write.run(); return null;
  363. }).when(vals).set(any(), any());
  364. when(redis.exec()).thenAnswer(i -> {
  365. if (beforeExec != null) { Runnable race = beforeExec; beforeExec = null; race.run(); }
  366. synchronized (values) {
  367. boolean conflict = watched.entrySet().stream().anyMatch(e -> !e.getValue().equals(versions.getOrDefault(e.getKey(), 0L)));
  368. if (conflict) { queued.clear(); multi[0] = false; watched.clear(); return null; }
  369. for (Runnable write : queued) write.run(); queued.clear(); multi[0] = false; watched.clear();
  370. return Collections.singletonList(Boolean.TRUE);
  371. }
  372. });
  373. when(redis.execute(any(SessionCallback.class))).thenAnswer(i -> ((SessionCallback) i.getArgument(0)).execute(redis));
  374. doAnswer(i -> { hash(i.getArgument(0).toString()).put(i.getArgument(1).toString(), serializer.serialize(i.getArgument(2))); return null; }).when(hash).put(any(), any(), any());
  375. when(hash.get(any(), any())).thenAnswer(i -> serializer.deserialize(hash(i.getArgument(0).toString()).get(i.getArgument(1).toString())));
  376. when(hash.values(any())).thenAnswer(i -> {
  377. List<Object> result = new ArrayList<>(); for (byte[] bytes : hash(i.getArgument(0).toString()).values()) result.add(serializer.deserialize(bytes)); return result;
  378. });
  379. when(hash.delete(any(), any())).thenAnswer(i -> hash(i.getArgument(0).toString()).remove(i.getArgument(1).toString()) == null ? 0L : 1L);
  380. when(hash.scan(any(), any(ScanOptions.class))).thenAnswer(i -> {
  381. String pattern = ((ScanOptions) i.getArgument(1)).getPattern().replace("*", ".*");
  382. Iterator<Map.Entry<Object,Object>> entries = new ArrayList<>(hash(i.getArgument(0).toString()).entrySet()).stream()
  383. .filter(e -> e.getKey().matches(pattern)).map(e -> (Map.Entry<Object,Object>) new AbstractMap.SimpleEntry<Object,Object>(e.getKey(), serializer.deserialize(e.getValue()))).iterator();
  384. Cursor<Map.Entry<Object,Object>> cursor = mock(Cursor.class);
  385. when(cursor.hasNext()).thenAnswer(a -> entries.hasNext()); when(cursor.next()).thenAnswer(a -> entries.next()); return cursor;
  386. });
  387. RedisConnection connection = mock(RedisConnection.class);
  388. when(redis.execute(any(RedisCallback.class))).thenAnswer(i -> ((RedisCallback<?>) i.getArgument(0)).doInRedis(connection));
  389. when(connection.eval(any(byte[].class), eq(ReturnType.INTEGER), anyInt(), org.mockito.ArgumentMatchers.<byte[][]>any())).thenAnswer(i -> {
  390. int n = i.getArgument(2);
  391. Object[] invocation = i.getArguments();
  392. byte[][] args = invocation.length == 4 && invocation[3] instanceof byte[][]
  393. ? (byte[][]) invocation[3] : Arrays.copyOfRange(invocation, 3, invocation.length, byte[][].class);
  394. synchronized (hashes) {
  395. for (int k = 0; k < n; k++) {
  396. int a = n + k * 5; byte[] expected = "1".equals(text(args[a+1])) ? args[a+2] : null;
  397. if (!Arrays.equals(expected, hash(text(args[k])).get(text(args[a])))) return 0L;
  398. }
  399. for (int k = 0; k < n; k++) {
  400. int a = n + k * 5;
  401. if ("1".equals(text(args[a+3]))) hash(text(args[k])).put(text(args[a]), args[a+4].clone());
  402. else hash(text(args[k])).remove(text(args[a]));
  403. }
  404. return 1L;
  405. }
  406. });
  407. return redis;
  408. }
  409. @SuppressWarnings("unchecked") StringRedisTemplate strings() {
  410. StringRedisTemplate redis = mock(StringRedisTemplate.class);
  411. ValueOperations<String,String> vals = mock(ValueOperations.class); SetOperations<String,String> sets = mock(SetOperations.class);
  412. when(redis.opsForValue()).thenReturn(vals); when(redis.opsForSet()).thenReturn(sets);
  413. when(vals.get(anyString())).thenAnswer(i -> (String) serializer.deserialize(values.get(i.getArgument(0))));
  414. doAnswer(i -> { values.put(i.getArgument(0), serializer.serialize(i.getArgument(1))); return null; }).when(vals).set(anyString(), anyString());
  415. when(sets.size(anyString())).thenReturn(100L); when(sets.pop(anyString())).thenAnswer(i -> String.format("12345%04d", ssrc.getAndIncrement()));
  416. return redis;
  417. }
  418. Map<String,byte[]> hash(String key) { return hashes.computeIfAbsent(key, unused -> new LinkedHashMap<>()); }
  419. static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
  420. }
  421. }