| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444 |
- package com.zksy.video.lifecycle;
- import com.alibaba.fastjson2.JSONObject;
- import com.ruoyi.wvp.common.*;
- import com.ruoyi.wvp.common.InviteInfo;
- import com.ruoyi.wvp.conf.*;
- import com.ruoyi.wvp.gb28181.SipLayer;
- import com.ruoyi.wvp.gb28181.bean.*;
- import com.ruoyi.wvp.gb28181.event.SipSubscribe;
- import com.ruoyi.wvp.gb28181.service.impl.*;
- import com.ruoyi.wvp.gb28181.session.*;
- import com.ruoyi.wvp.gb28181.transmit.*;
- import com.ruoyi.wvp.gb28181.transmit.cmd.SIPRequestHeaderProvider;
- import com.ruoyi.wvp.gb28181.transmit.cmd.impl.SIPCommander;
- import com.ruoyi.wvp.mapper.*;
- import com.ruoyi.wvp.media.bean.MediaServer;
- import com.ruoyi.wvp.media.event.hook.HookSubscribe;
- import com.ruoyi.wvp.media.service.impl.MediaServerServiceImpl;
- import com.ruoyi.wvp.media.zlm.*;
- import com.ruoyi.wvp.service.bean.*;
- import com.ruoyi.wvp.service.impl.RtpServerServiceImpl;
- import com.ruoyi.wvp.storager.impl.RedisCatchStorageImpl;
- import com.ruoyi.wvp.utils.redis.FastJsonRedisSerializer;
- import gov.nist.javax.sip.message.SIPResponse;
- import org.junit.jupiter.api.Test;
- import org.springframework.data.redis.connection.*;
- import org.springframework.data.redis.core.*;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
- import org.springframework.test.util.ReflectionTestUtils;
- import javax.sip.*;
- import javax.sip.header.*;
- import javax.sip.message.Request;
- import java.nio.charset.StandardCharsets;
- import java.util.*;
- import java.util.concurrent.atomic.AtomicInteger;
- import java.util.function.Predicate;
- import static org.junit.jupiter.api.Assertions.*;
- import static org.mockito.ArgumentMatchers.*;
- import static org.mockito.Mockito.*;
- /** Real Play/RTP/Hook/Invite/Session/Commander/header/media modules; only I/O and timer are substituted. */
- class VideoStopReceiptRestartTest {
- private static final String STREAM = "managed_11111111111111111111111111111111";
- private static final String LEGACY = "device_channel";
- @Test void positiveRtpReceiptSurvivesRebuildingBothRtpAndReceiptModule() throws Exception {
- External world = new External(); Instance first = new Instance(world);
- SSRCInfo allocation = first.open(STREAM); assertNotNull(allocation);
- assertTrue(first.rtp.closeManagedRTPServer(world.node, allocation));
- Instance second = new Instance(world);
- assertTrue(second.rtp.closeManagedRTPServer(world.node, allocation));
- assertEquals(1, world.closeRequests.size());
- assertNull(second.open(STREAM));
- }
- @Test void rebuiltRtpReturnsItsOriginalSsrcWithoutReturningAReusedNumberAgain() throws Exception {
- External world = new External();
- String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
- world.ssrcRedis.strings().delete(pool);
- world.ssrcRedis.strings().opsForSet().add(pool, "200000001");
- SSRCInfo original = new Instance(world).open(STREAM);
- assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
- assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, original));
- assertEquals(1L, world.ssrcRedis.strings().opsForSet().size(pool));
- SSRCInfo another = new Instance(world).open("other_legacy_stream");
- assertNotNull(another); assertEquals(original.getSsrc(), another.getSsrc());
- assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
- assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, original));
- assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool), "a duplicate close never makes an occupied number available");
- assertTrue(world.open.contains("other_legacy_stream"));
- }
- @Test void negotiatedSsrcKeepsTheOriginalPoolNumberForCloseAndReturn() throws Exception {
- External world = new External();
- Instance instance = new Instance(world);
- String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
- world.ssrcRedis.strings().delete(pool);
- world.ssrcRedis.strings().opsForSet().add(pool, "200000001");
- SSRCInfo original = instance.open(STREAM);
- // The device renegotiates a different SSRC while the original pool number stays owned.
- String negotiated = "0999999999";
- assertTrue(instance.receipts.recordNegotiatedSsrc(world.node.getId(), STREAM, original, negotiated, false));
- SSRCInfo current = new SSRCInfo(original.getPort(), negotiated, "rtp", STREAM, original.getTimeOutTaskKey());
- assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, current));
- assertEquals(1L, world.ssrcRedis.strings().opsForSet().size(pool), "the original pool number is returned once");
- // The next allocation proves which number came back: the original, never the negotiated one.
- assertEquals(original.getSsrc(), new Instance(world).open("next_stream").getSsrc());
- assertEquals(0L, world.ssrcRedis.strings().opsForSet().size(pool));
- }
- @Test void delayedLegacyCloseReturnsSsrcWhenTheCallerNeverRetries() throws Exception {
- External world = new External(); world.delayClose = true;
- Instance instance = new Instance(world);
- SSRCInfo allocation = instance.open(LEGACY);
- String pool = "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a";
- assertEquals(99L, world.ssrcRedis.strings().opsForSet().size(pool));
- instance.rtp.closeRTPServer(world.node, allocation);
- assertEquals(99L, world.ssrcRedis.strings().opsForSet().size(pool));
- world.closeReplies.get(0).run();
- assertEquals(100L, world.ssrcRedis.strings().opsForSet().size(pool), "the positive async receipt must finish pool cleanup without a second stop call");
- assertEquals(1, world.closeRequests.size());
- }
- @Test void managedStopRecoversOriginalDialogAfterByeReceiptAndLiveDialogDeletion() throws Exception {
- External world = new External(); Instance first = new Instance(world);
- first.managed();
- assertFalse(first.stopManaged());
- assertTrue(first.hooks.getAll().isEmpty());
- Request bye = world.lastBye();
- // Fresh observer has no SipSubscribe callbacks. Only serialized Redis state survives.
- Instance second = new Instance(world); second.response(bye, 200);
- assertNull(second.sessions.getSsrcTransactionByStream("rtp", STREAM));
- assertTrue(second.stopManaged());
- assertTrue(new Instance(world).stopManaged());
- assertEquals(1, world.closeRequests.size());
- }
- @Test void successfulSendAndRtpCloseWithoutBye2xxStayPendingAfterRestart() throws Exception {
- External world = new External(); Instance first = new Instance(world); first.managed();
- assertFalse(first.stopManaged());
- Instance second = new Instance(world);
- assertFalse(second.stopManaged());
- second.response(world.lastBye(), 500);
- assertFalse(new Instance(world).stopManaged());
- assertEquals(1, world.closeRequests.size());
- }
- @Test void adoptedStopRecoversAndOldHandleCannotCloseSameNameReplacement() throws Exception {
- External world = new External(); Instance first = new Instance(world);
- SSRCInfo original = first.legacy("call-old"); String handle = first.adopt(); assertNotNull(handle);
- assertFalse(first.stopAdopted(handle)); Request bye = world.lastBye();
- Instance second = new Instance(world); second.response(bye, 200);
- assertTrue(second.stopAdopted(handle));
- SSRCInfo replacement = second.legacy("call-new");
- assertNotEquals(original.getTimeOutTaskKey(), replacement.getTimeOutTaskKey());
- Instance third = new Instance(world);
- assertFalse(third.stopAdopted(handle));
- assertFalse(third.rtp.closeAdoptedRTPServer(world.node, original, "call-old"));
- third.rtp.closeRTPServer(world.node, original); // a late ordinary timeout uses the same allocation fence
- assertEquals(1, world.closeRequests.size());
- assertTrue(world.open.contains(LEGACY));
- assertEquals("call-new", third.sessions.getSsrcTransactionByStream("rtp", LEGACY).getCallId());
- }
- @Test void unknownNameCloseIsNotRepeatedAndCannotReopenEvenAfterBye2xxAndRestart() throws Exception {
- External world = new External(); world.delayClose = true;
- Instance first = new Instance(world); first.legacy("call-old"); String handle = first.adopt();
- assertFalse(first.stopAdopted(handle));
- Instance second = new Instance(world); second.response(world.lastBye(), 200);
- assertFalse(second.stopAdopted(handle)); assertNull(second.open(LEGACY));
- assertEquals(1, world.closeRequests.size()); assertEquals(1, world.openRequests.get());
- world.closeReplies.get(0).run();
- assertTrue(new Instance(world).stopAdopted(handle));
- }
- @Test void hitZeroAndNonzeroCodeAreNotDurableCloseEvidence() throws Exception {
- for (String reply : List.of("{\"code\":0,\"hit\":0}", "{\"code\":-1,\"hit\":1}")) {
- External world = new External(); world.closeReply = reply;
- Instance first = new Instance(world); first.managed(); assertFalse(first.stopManaged());
- Instance second = new Instance(world); second.response(world.lastBye(), 200);
- assertFalse(second.stopManaged()); assertFalse(new Instance(world).stopManaged());
- assertEquals(1, world.closeRequests.size());
- }
- }
- @Test void positiveCallbackWithFailedReceiptWriteCannotBeMaskedByLocalSuccess() throws Exception {
- External world = new External(); Instance first = new Instance(world); first.managed();
- world.redis.failWrite = value -> value.contains("\"state\":\"CLOSED\"");
- assertFalse(first.stopManaged());
- world.redis.failWrite = value -> false;
- first.response(world.lastBye(), 200);
- assertFalse(first.stopManaged()); assertFalse(new Instance(world).stopManaged());
- assertEquals(1, world.closeRequests.size());
- }
- @Test void failedIntentWriteNeverDispatchesCreateAndMissingReceiptIsNotStopped() throws Exception {
- External world = new External(); Instance first = new Instance(world);
- world.redis.failWrite = value -> true;
- assertThrows(RuntimeException.class, () -> first.play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { }));
- world.redis.failWrite = value -> false;
- assertFalse(new Instance(world).stopManaged());
- assertEquals(0, world.openRequests.get()); assertTrue(world.requests.isEmpty());
- }
- @Test void closeCompareAndSetLoserCannotDispatchASecondNameClose() throws Exception {
- External world = new External(); Instance first = new Instance(world), second = new Instance(world);
- SSRCInfo allocation = first.open(STREAM);
- world.redis.beforeExec = () -> assertTrue(second.rtp.closeManagedRTPServer(world.node, allocation));
- assertFalse(first.rtp.closeManagedRTPServer(world.node, allocation));
- assertTrue(new Instance(world).rtp.closeManagedRTPServer(world.node, allocation));
- assertEquals(1, world.closeRequests.size());
- }
- @Test void managedUuidCannotBeReallocatedOnAnotherNodeAfterReconstruction() throws Exception {
- External world = new External(); Instance first = new Instance(world);
- SSRCInfo allocation = first.open(STREAM); assertTrue(first.rtp.closeManagedRTPServer(world.node, allocation));
- MediaServer other = new MediaServer(); other.setId("node-b"); other.setType("zlm"); other.setRtpEnable(true);
- RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(other); param.setStreamId(STREAM);
- Instance second = new Instance(world);
- assertNull(second.rtp.openRTPServer(param, (c, m, r) -> { }));
- assertFalse(second.rtp.closeManagedRTPServer(other, allocation));
- assertEquals(1, world.openRequests.get()); assertEquals(1, world.closeRequests.size());
- }
- @Test void oldConfirmationCannotAuthorizeChangedTagsEvenIfCallIdAndSsrcWereReused() throws Exception {
- External world = new External(); Instance first = new Instance(world);
- first.legacy("reused-call"); String handle = first.adopt(); assertFalse(first.stopAdopted(handle));
- Request oldBye = world.lastBye();
- Instance second = new Instance(world);
- SsrcTransaction replacement = second.sessions.getSsrcTransactionByStream("rtp", LEGACY);
- replacement.getSipTransactionInfo().setToTag("new-dialog-tag"); second.sessions.put(replacement);
- second.response(oldBye, 200);
- Instance third = new Instance(world);
- assertFalse(third.stopAdopted(handle));
- assertEquals("new-dialog-tag", third.sessions.getSsrcTransactionByStream("rtp", LEGACY).getSipTransactionInfo().getToTag());
- assertEquals(1, world.closeRequests.size());
- }
- @Test void lostCreateResultRemainsCreatingAcrossRestartWithoutCloseOrReopen() throws Exception {
- External world = new External(); world.throwDuringOpen = true;
- Instance first = new Instance(world); assertNull(first.open(STREAM));
- Instance second = new Instance(world);
- assertNull(second.open(STREAM));
- assertTrue(world.closeRequests.isEmpty()); assertEquals(1, world.openRequests.get());
- }
- static class Instance {
- final PlayServiceImpl play = new PlayServiceImpl();
- final RtpServerServiceImpl rtp = new RtpServerServiceImpl();
- final HookSubscribe hooks = new HookSubscribe();
- final InviteStreamServiceImpl invites = new InviteStreamServiceImpl();
- final SipInviteSessionManager sessions = new SipInviteSessionManager();
- final SIPProcessorObserver observer = new SIPProcessorObserver();
- final SIPCommander commander = new SIPCommander();
- final External world;
- final VideoStopReceipts receipts;
- Instance(External world) throws Exception {
- this.world = world;
- UserSetting settings = new UserSetting(); settings.setServerId("restart-test"); settings.setPlayTimeout(30000);
- RedisTemplate<Object,Object> redis = world.redis.client();
- StringRedisTemplate strings = world.redis.strings();
- receipts = new VideoStopReceipts(redis);
- RedisVideoLifecycleStore lifecycle = new RedisVideoLifecycleStore(strings);
- SSRCFactory ssrc = new SSRCFactory(); wire(ssrc, "redisTemplate", world.ssrcRedis.strings()); wire(ssrc, "userSetting", settings);
- wire(invites, "redisTemplate", redis); wire(invites, "userSetting", settings);
- wire(sessions, "redisTemplate", redis); wire(sessions, "userSetting", settings);
- RedisCatchStorageImpl cache = new RedisCatchStorageImpl();
- wire(cache, "redisTemplate", redis); wire(cache, "userSetting", settings); cache.updateDevice(world.device);
- DeviceMapper devices = mock(DeviceMapper.class); DeviceChannelMapper channels = mock(DeviceChannelMapper.class);
- when(devices.getDeviceByDeviceId("device")).thenReturn(world.device);
- when(channels.getOneByDeviceIdForSource(1, "channel")).thenReturn(world.channel);
- DeviceChannelServiceImpl channelService = new DeviceChannelServiceImpl();
- wire(channelService, "deviceMapper", devices); wire(channelService, "channelMapper", channels);
- ZLMServerFactory zlm = new ZLMServerFactory(); wire(zlm, "zlmresTfulUtils", world.zlm);
- ZLMMediaNodeServerService zlmNode = new ZLMMediaNodeServerService(); wire(zlmNode, "zlmServerFactory", zlm);
- MediaServerServiceImpl media = new MediaServerServiceImpl(); wire(media, "nodeServerServiceMap", Map.of("zlm", zlmNode));
- wire(rtp, "mediaServerService", media); wire(rtp, "dynamicTask", mock(DynamicTask.class));
- wire(rtp, "ssrcFactory", ssrc); wire(rtp, "userSetting", settings); wire(rtp, "subscribe", hooks);
- wire(rtp, "sessionManager", sessions); wire(rtp, "videoLifecycleStore", lifecycle); wire(rtp, "stopReceipts", receipts);
- SipConfig sipConfig = new SipConfig(); sipConfig.setId("34020000002000000001"); sipConfig.setDomain("3402000000"); sipConfig.setPort(5060);
- SipLayer layer = mock(SipLayer.class); when(layer.getLocalIp(any())).thenReturn("127.0.0.1");
- SIPRequestHeaderProvider headers = new SIPRequestHeaderProvider();
- wire(headers, "sipConfig", sipConfig); wire(headers, "sipLayer", layer); wire(headers, "redisCatchStorage", cache);
- wire(commander, "headerProvider", headers); wire(commander, "sessionManager", sessions);
- wire(commander, "sipSender", world.sender); wire(commander, "sipLayer", layer);
- wire(commander, "sipConfig", sipConfig); wire(commander, "userSetting", settings); wire(commander, "videoLifecycleStore", lifecycle);
- wire(observer, "sessionManager", sessions); wire(observer, "sipSubscribe", new SipSubscribe());
- wire(play, "cmder", commander); wire(play, "redisCatchStorage", cache); wire(play, "deviceChannelService", channelService);
- wire(play, "inviteStreamService", invites); wire(play, "sessionManager", sessions); wire(play, "subscribe", hooks);
- wire(play, "receiveRtpServerService", rtp); wire(play, "mediaServerService", media);
- wire(play, "videoLifecycleStore", lifecycle); wire(play, "userSetting", settings); wire(play, "stopReceipts", receipts);
- }
- SSRCInfo open(String stream) {
- RTPServerParam param = new RTPServerParam(); param.setMediaServerItem(world.node); param.setStreamId(stream);
- return rtp.openRTPServer(param, (code, msg, result) -> { });
- }
- void managed() throws Exception {
- SSRCInfo info = play.playManaged(world.node, "device", "channel", STREAM, (c, m, r) -> { }); assertNotNull(info);
- Request invite = world.requests.get(world.requests.size() - 1); assertEquals(Request.INVITE, invite.getMethod());
- SIPResponse reply = reply(invite, 200);
- reply.setContent("v=0\r\ns=Play\r\ny=" + info.getSsrc() + "\r\n",
- SipFactory.getInstance().createHeaderFactory().createContentTypeHeader("application", "sdp"));
- world.inviteCallbacks.get(invite).response(new SipSubscribe.EventResult<>(new ResponseEvent(this, null, null, reply)));
- assertNotNull(sessions.getSsrcTransactionByStream("rtp", STREAM));
- }
- SSRCInfo legacy(String call) {
- SSRCInfo info = open(LEGACY); assertNotNull(info);
- invites.updateInviteInfo(InviteInfo.getInviteInfo("device", 7, LEGACY, info, "node-a", "127.0.0.1", 30000,
- "UDP", InviteSessionType.PLAY, InviteSessionStatus.ready, false));
- SsrcTransaction tx = new SsrcTransaction(); tx.setApp("rtp"); tx.setStream(LEGACY); tx.setDeviceId("device");
- tx.setChannelId(7); tx.setMediaServerId("node-a"); tx.setSsrc(info.getSsrc()); tx.setCallId(call); tx.setType(InviteSessionType.PLAY);
- SipTransactionInfo sip = new SipTransactionInfo(); sip.setCallId(call); sip.setFromTag("from-old");
- sip.setToTag("to-old"); sip.setViaBranch("z9hG4bK-old"); tx.setSipTransactionInfo(sip); sessions.put(tx); return info;
- }
- String adopt() { return play.adoptStream(world.node, world.device, world.channel, LEGACY, null); }
- boolean stopAdopted(String handle) { return play.stopAdopted(world.node, world.device, world.channel, LEGACY, handle); }
- boolean stopManaged() { return play.stopManaged(world.node, world.device, world.channel, STREAM); }
- void response(Request request, int status) throws Exception { observer.processResponse(new ResponseEvent(this, null, null, reply(request, status))); }
- }
- static SIPResponse reply(Request request, int status) throws Exception {
- SIPResponse reply = (SIPResponse) SipFactory.getInstance().createMessageFactory().createResponse(status, request);
- if (reply.getToTag() == null) reply.getTo().setTag("to-managed");
- return reply;
- }
- static class External {
- final RedisMemory redis = new RedisMemory();
- final ZLMRESTfulUtils zlm = mock(ZLMRESTfulUtils.class);
- final SIPSender sender = mock(SIPSender.class);
- final MediaServer node = new MediaServer(); final Device device = new Device(); final DeviceChannel channel = new DeviceChannel();
- final Set<String> open = new HashSet<>(); final List<String> closeRequests = new ArrayList<>();
- final List<Runnable> closeReplies = new ArrayList<>(); final List<Request> requests = new ArrayList<>();
- final Map<Request, SipSubscribe.Event> inviteCallbacks = new IdentityHashMap<>();
- final AtomicInteger openRequests = new AtomicInteger(), calls = new AtomicInteger();
- boolean delayClose, throwDuringOpen;
- String closeReply = "{\"code\":0,\"hit\":1}";
- final FakeStringRedis ssrcRedis = new FakeStringRedis();
- External() throws Exception {
- for (int i = 1; i <= 100; i++) ssrcRedis.strings().opsForSet().add(
- "CITY_VIDEO_VMP_SSRC_INFO_restart-test_node-a", String.format("20000%04d", i));
- node.setId("node-a"); node.setType("zlm"); node.setRtpEnable(true); node.setSdpIp("127.0.0.1");
- device.setId(1); device.setDeviceId("device"); device.setStreamMode("UDP"); device.setTransport("UDP"); device.setHostAddress("127.0.0.2:5060");
- channel.setId(7); channel.setDeviceId("channel");
- when(zlm.getRtpInfo(any(), anyString())).thenReturn(JSONObject.parseObject("{\"code\":0,\"exist\":false}"));
- when(zlm.openRtpServer(any(), anyMap())).thenAnswer(i -> {
- openRequests.incrementAndGet(); open.add((String) ((Map<?,?>) i.getArgument(1)).get("stream_id"));
- if (throwDuringOpen) throw new IllegalStateException("response lost after dispatch");
- return JSONObject.parseObject("{\"code\":0,\"port\":30000}");
- });
- doAnswer(i -> {
- String stream = (String) ((Map<?,?>) i.getArgument(1)).get("stream_id"); closeRequests.add(stream);
- ZLMRESTfulUtils.RequestCallback callback = i.getArgument(2);
- Runnable reply = () -> {
- JSONObject result = JSONObject.parseObject(closeReply);
- if (Integer.valueOf(0).equals(result.getInteger("code")) && Integer.valueOf(1).equals(result.getInteger("hit"))) open.remove(stream);
- callback.run(result);
- };
- closeReplies.add(reply); if (!delayClose) reply.run(); return null;
- }).when(zlm).closeRtpServer(any(), anyMap(), any());
- when(sender.getNewCallIdHeader(anyString(), anyString())).thenAnswer(i -> SipFactory.getInstance().createHeaderFactory().createCallIdHeader("call-" + calls.incrementAndGet()));
- doAnswer(i -> { requests.add(i.getArgument(1)); return null; }).when(sender).transmitRequest(any(), any(), any(), any());
- doAnswer(i -> { Request request = i.getArgument(1); requests.add(request); inviteCallbacks.put(request, i.getArgument(3)); return null; })
- .when(sender).transmitRequest(any(), any(), any(), any(), anyLong());
- }
- Request lastBye() { return requests.stream().filter(r -> Request.BYE.equals(r.getMethod())).reduce((a, b) -> b).orElseThrow(); }
- }
- static void wire(Object target, String field, Object dependency) {
- ReflectionTestUtils.setField(target, field, dependency); // dependency injection only, never business state
- }
- /** Serialized external Redis substitute, including WATCH conflicts and all-or-nothing SIP hash CAS. */
- static class RedisMemory {
- final Map<String, byte[]> values = new HashMap<>();
- final Map<String, Map<String, byte[]>> hashes = new HashMap<>();
- final Map<String, Long> versions = new HashMap<>();
- final FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
- final StringRedisSerializer strings = new StringRedisSerializer();
- final AtomicInteger ssrc = new AtomicInteger(1), sequence = new AtomicInteger();
- Predicate<String> failWrite = value -> false;
- Runnable beforeExec;
- @SuppressWarnings({"unchecked", "rawtypes"})
- RedisTemplate<Object,Object> client() {
- RedisTemplate<Object,Object> redis = mock(RedisTemplate.class);
- ValueOperations<Object,Object> vals = mock(ValueOperations.class); HashOperations<Object,Object,Object> hash = mock(HashOperations.class);
- when(redis.opsForValue()).thenReturn(vals); when(redis.opsForHash()).thenReturn(hash);
- when(redis.getKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
- when(redis.getHashKeySerializer()).thenReturn((org.springframework.data.redis.serializer.RedisSerializer) strings);
- doReturn(serializer).when(redis).getHashValueSerializer();
- Map<String,Long> watched = new HashMap<>(); List<Runnable> queued = new ArrayList<>(); boolean[] multi = { false };
- doAnswer(i -> { String key = i.getArgument(0).toString(); watched.put(key, versions.getOrDefault(key, 0L)); return null; }).when(redis).watch(any(Object.class));
- doAnswer(i -> { multi[0] = true; return null; }).when(redis).multi();
- doAnswer(i -> { multi[0] = false; queued.clear(); watched.clear(); return null; }).when(redis).discard();
- doAnswer(i -> { watched.clear(); return null; }).when(redis).unwatch();
- when(vals.get(any())).thenAnswer(i -> serializer.deserialize(values.get(i.getArgument(0).toString())));
- when(vals.increment(any(), anyLong())).thenAnswer(i -> (long) sequence.incrementAndGet());
- doAnswer(i -> {
- String key = i.getArgument(0).toString(); Object value = i.getArgument(1); byte[] encoded = serializer.serialize(value);
- Runnable write = () -> {
- if (failWrite.test(value.toString())) throw new IllegalStateException("Redis write unavailable");
- values.put(key, encoded); versions.merge(key, 1L, Long::sum);
- };
- if (multi[0]) queued.add(write); else write.run(); return null;
- }).when(vals).set(any(), any());
- when(redis.exec()).thenAnswer(i -> {
- if (beforeExec != null) { Runnable race = beforeExec; beforeExec = null; race.run(); }
- synchronized (values) {
- boolean conflict = watched.entrySet().stream().anyMatch(e -> !e.getValue().equals(versions.getOrDefault(e.getKey(), 0L)));
- if (conflict) { queued.clear(); multi[0] = false; watched.clear(); return null; }
- for (Runnable write : queued) write.run(); queued.clear(); multi[0] = false; watched.clear();
- return Collections.singletonList(Boolean.TRUE);
- }
- });
- when(redis.execute(any(SessionCallback.class))).thenAnswer(i -> ((SessionCallback) i.getArgument(0)).execute(redis));
- 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());
- when(hash.get(any(), any())).thenAnswer(i -> serializer.deserialize(hash(i.getArgument(0).toString()).get(i.getArgument(1).toString())));
- when(hash.values(any())).thenAnswer(i -> {
- List<Object> result = new ArrayList<>(); for (byte[] bytes : hash(i.getArgument(0).toString()).values()) result.add(serializer.deserialize(bytes)); return result;
- });
- when(hash.delete(any(), any())).thenAnswer(i -> hash(i.getArgument(0).toString()).remove(i.getArgument(1).toString()) == null ? 0L : 1L);
- when(hash.scan(any(), any(ScanOptions.class))).thenAnswer(i -> {
- String pattern = ((ScanOptions) i.getArgument(1)).getPattern().replace("*", ".*");
- Iterator<Map.Entry<Object,Object>> entries = new ArrayList<>(hash(i.getArgument(0).toString()).entrySet()).stream()
- .filter(e -> e.getKey().matches(pattern)).map(e -> (Map.Entry<Object,Object>) new AbstractMap.SimpleEntry<Object,Object>(e.getKey(), serializer.deserialize(e.getValue()))).iterator();
- Cursor<Map.Entry<Object,Object>> cursor = mock(Cursor.class);
- when(cursor.hasNext()).thenAnswer(a -> entries.hasNext()); when(cursor.next()).thenAnswer(a -> entries.next()); return cursor;
- });
- 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 -> {
- 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);
- synchronized (hashes) {
- 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, hash(text(args[k])).get(text(args[a])))) return 0L;
- }
- for (int k = 0; k < n; k++) {
- int a = n + k * 5;
- if ("1".equals(text(args[a+3]))) hash(text(args[k])).put(text(args[a]), args[a+4].clone());
- else hash(text(args[k])).remove(text(args[a]));
- }
- return 1L;
- }
- });
- return redis;
- }
- @SuppressWarnings("unchecked") StringRedisTemplate strings() {
- StringRedisTemplate redis = mock(StringRedisTemplate.class);
- ValueOperations<String,String> vals = mock(ValueOperations.class); SetOperations<String,String> sets = mock(SetOperations.class);
- when(redis.opsForValue()).thenReturn(vals); when(redis.opsForSet()).thenReturn(sets);
- when(vals.get(anyString())).thenAnswer(i -> (String) serializer.deserialize(values.get(i.getArgument(0))));
- doAnswer(i -> { values.put(i.getArgument(0), serializer.serialize(i.getArgument(1))); return null; }).when(vals).set(anyString(), anyString());
- when(sets.size(anyString())).thenReturn(100L); when(sets.pop(anyString())).thenAnswer(i -> String.format("12345%04d", ssrc.getAndIncrement()));
- return redis;
- }
- Map<String,byte[]> hash(String key) { return hashes.computeIfAbsent(key, unused -> new LinkedHashMap<>()); }
- static String text(byte[] value) { return new String(value, StandardCharsets.UTF_8); }
- }
- }
|