|
@@ -0,0 +1,367 @@
|
|
|
|
|
+package com.zksy.web.controller.cockpit;
|
|
|
|
|
+
|
|
|
|
|
+import com.alibaba.fastjson2.JSON;
|
|
|
|
|
+import com.alibaba.fastjson2.JSONObject;
|
|
|
|
|
+import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
|
|
|
|
+import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
|
|
|
|
+import com.zksy.base.domain.EquipmentBase;
|
|
|
|
|
+import com.zksy.base.mapper.EquipmentBaseMapper;
|
|
|
|
|
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
|
|
|
|
|
+import com.zksy.base.mapper.VideoSessionMapper;
|
|
|
|
|
+import com.zksy.base.video.VideoCollectorClient;
|
|
|
|
|
+import com.zksy.base.video.VideoDeviceRecord;
|
|
|
|
|
+import com.zksy.base.video.VideoSession;
|
|
|
|
|
+import org.apache.ibatis.builder.MapperBuilderAssistant;
|
|
|
|
|
+import org.junit.jupiter.api.AfterEach;
|
|
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
|
|
+import org.springframework.beans.BeanUtils;
|
|
|
|
|
+import org.springframework.context.annotation.Bean;
|
|
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
|
|
+import org.springframework.context.annotation.Import;
|
|
|
|
|
+import org.springframework.core.env.MapPropertySource;
|
|
|
|
|
+import org.springframework.http.MediaType;
|
|
|
|
|
+import org.springframework.mock.web.MockServletContext;
|
|
|
|
|
+import org.springframework.security.core.context.SecurityContextHolder;
|
|
|
|
|
+import org.springframework.test.web.servlet.MockMvc;
|
|
|
|
|
+import org.springframework.test.web.servlet.ResultActions;
|
|
|
|
|
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|
|
|
|
+import org.springframework.transaction.support.AbstractPlatformTransactionManager;
|
|
|
|
|
+import org.springframework.transaction.support.DefaultTransactionStatus;
|
|
|
|
|
+import org.springframework.transaction.TransactionDefinition;
|
|
|
|
|
+import org.springframework.transaction.support.TransactionSynchronizationManager;
|
|
|
|
|
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
|
|
|
|
+
|
|
|
|
|
+import javax.servlet.Filter;
|
|
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
|
|
+import java.util.ArrayList;
|
|
|
|
|
+import java.util.HashSet;
|
|
|
|
|
+import java.util.LinkedHashMap;
|
|
|
|
|
+import java.util.List;
|
|
|
|
|
+import java.util.Map;
|
|
|
|
|
+import java.util.Set;
|
|
|
|
|
+import java.util.stream.Collectors;
|
|
|
|
|
+
|
|
|
|
|
+import static org.junit.jupiter.api.Assertions.*;
|
|
|
|
|
+import static org.mockito.ArgumentMatchers.*;
|
|
|
|
|
+import static org.mockito.Mockito.*;
|
|
|
|
|
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
|
|
|
|
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
|
|
|
|
+
|
|
|
|
|
+/** Prepared lifecycle at HTTP + real security/service/transaction seams.
|
|
|
|
|
+ * DB rows/commit outcome and media transport are adapters; no shared-count algorithm is copied here.
|
|
|
|
|
+ */
|
|
|
|
|
+class VideoPreparedSessionTest {
|
|
|
|
|
+ private static final String ROOT = "/api/cockpit/v1/video";
|
|
|
|
|
+ private static final String CODE = "摄像机/ PREPARED+01";
|
|
|
|
|
+ private static final String VIDEO = "prepared-ledger-id";
|
|
|
|
|
+ private static final java.util.regex.Pattern UUID_PARAM = java.util.regex.Pattern.compile(
|
|
|
|
|
+ "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}");
|
|
|
|
|
+ private AnnotationConfigWebApplicationContext context;
|
|
|
|
|
+ private MockMvc mvc;
|
|
|
|
|
+ private VideoSessionMapper sessions;
|
|
|
|
|
+ private VideoCollectorClient media;
|
|
|
|
|
+ private RowTransactions transactions;
|
|
|
|
|
+
|
|
|
|
|
+ @BeforeEach void setUp() {
|
|
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
|
|
+ TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), VideoSession.class);
|
|
|
|
|
+ context = new AnnotationConfigWebApplicationContext();
|
|
|
|
|
+ context.setServletContext(new MockServletContext());
|
|
|
|
|
+ context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("prepared-test", Map.of(
|
|
|
|
|
+ "token.header", "Authorization", "token.secret", "prepared-offline-contract-not-a-production-secret", "token.expireTime", "60")));
|
|
|
|
|
+ context.register(ConfigurationUnderTest.class);
|
|
|
|
|
+ context.refresh();
|
|
|
|
|
+ mvc = MockMvcBuilders.webAppContextSetup(context)
|
|
|
|
|
+ .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
|
|
|
|
|
+ sessions = context.getBean(VideoSessionMapper.class);
|
|
|
|
|
+ media = context.getBean(VideoCollectorClient.class);
|
|
|
|
|
+ transactions = context.getBean(RowTransactions.class);
|
|
|
|
|
+ EquipmentBase device = new EquipmentBase();
|
|
|
|
|
+ device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("准备态摄像机"); device.setEquipmentTypeId(20);
|
|
|
|
|
+ when(context.getBean(EquipmentBaseMapper.class).selectList(any())).thenReturn(List.of(device));
|
|
|
|
|
+ VideoDeviceRecord binding = new VideoDeviceRecord(); BeanUtils.copyProperties(device, binding);
|
|
|
|
|
+ binding.setVideoId(VIDEO); binding.setSourceType("GB28181");
|
|
|
|
|
+ binding.setGbDeviceId("34020000002000000001"); binding.setGbChannelId("34020000001320000001");
|
|
|
|
|
+ when(context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO)).thenReturn(binding);
|
|
|
|
|
+ when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
|
|
|
|
|
+ assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "identity must be persisted in a transaction");
|
|
|
|
|
+ VideoSession row = call.getArgument(0);
|
|
|
|
|
+ transactions.rows().put(row.getSessionId(), copy(row)); return 1;
|
|
|
|
|
+ });
|
|
|
|
|
+ when(sessions.selectById(anyString())).thenAnswer(call -> copy(transactions.rows().get(call.getArgument(0))));
|
|
|
|
|
+ when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
|
|
|
|
|
+ VideoSession row = call.getArgument(0);
|
|
|
|
|
+ return transactions.rows().replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
|
|
|
|
|
+ });
|
|
|
|
|
+ when(sessions.lockVideo(VIDEO)).thenAnswer(call -> {
|
|
|
|
|
+ assertTrue(TransactionSynchronizationManager.isActualTransactionActive(), "device lock requires a short DB transaction");
|
|
|
|
|
+ return VIDEO;
|
|
|
|
|
+ });
|
|
|
|
|
+ // 内存适配器只做“数据库会给出的答案”,共享/代次判定仍在生产代码里。
|
|
|
|
|
+ when(sessions.selectList(any())).thenAnswer(call -> new ArrayList<>(
|
|
|
|
|
+ matching(paramsOf(call.getArgument(0))).stream().map(VideoPreparedSessionTest::copy).collect(Collectors.toList())));
|
|
|
|
|
+ when(sessions.selectCount(any())).thenAnswer(call -> (long) matching(paramsOf(call.getArgument(0))).size());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @AfterEach void close() {
|
|
|
|
|
+ if (context != null) context.close();
|
|
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void prepareCommitsKnownOwnershipBeforeAnyMediaAndStoppedIdentityCannotStartLater() throws Exception {
|
|
|
|
|
+ JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
|
|
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
|
|
|
|
|
+ .andExpect(status().isCreated()).andExpect(jsonPath("$.code").value(200))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("PREPARED"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.deviceCode").value(CODE))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.sessionId").isNotEmpty())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.mediaGeneration").doesNotExist())
|
|
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ action(viewer, "status", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("PREPARED"));
|
|
|
|
|
+ action(viewer, "stop", "A".repeat(43)).andExpect(status().isForbidden());
|
|
|
|
|
+ action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("STOPPED"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media").doesNotExist());
|
|
|
|
|
+ verifyNoInteractions(media);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void knownIdentityStartsAndStopsOneExactGenerationOutsideSqlTransactions() throws Exception {
|
|
|
|
|
+ java.util.concurrent.atomic.AtomicReference<Map<String,Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
|
|
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
|
|
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "never hold a DB transaction while starting media");
|
|
|
|
|
+ Map<String,Object> request = call.getArgument(1);
|
|
|
|
|
+ assertEquals(Map.of("type", "GB28181", "videoId", VIDEO, "deviceId", "34020000002000000001",
|
|
|
|
|
+ "channelId", "34020000001320000001"), request.get("source"));
|
|
|
|
|
+ assertEquals(java.time.Instant.parse("2026-11-10T08:00:30Z").toEpochMilli(), request.get("startDeadline"));
|
|
|
|
|
+ assertTrue(request.get("generation") instanceof String);
|
|
|
|
|
+ assertNotNull(java.util.UUID.fromString((String) request.get("generation")));
|
|
|
|
|
+ started.set(new LinkedHashMap<>(request));
|
|
|
|
|
+ return Map.of("generation", request.get("generation"), "status", "ACTIVE", "media",
|
|
|
|
|
+ Map.of("stream", "prepared_stream", "flv", "https://media.invalid/prepared.flv", "secret", "internal-secret"));
|
|
|
|
|
+ });
|
|
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/status"), any())).thenAnswer(call -> {
|
|
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "status must not hold a SQL lock");
|
|
|
|
|
+ Map<String,Object> request = call.getArgument(1);
|
|
|
|
|
+ assertEquals(started.get().get("generation"), request.get("generation"));
|
|
|
|
|
+ assertEquals(started.get().get("startDeadline"), request.get("startDeadline"));
|
|
|
|
|
+ return Map.of("generation", request.get("generation"), "status", "ACTIVE", "media",
|
|
|
|
|
+ Map.of("stream", "prepared_stream", "flv", "https://media.invalid/prepared.flv"));
|
|
|
|
|
+ });
|
|
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive(), "cancel must not hold a SQL lock");
|
|
|
|
|
+ Map<String,Object> request = call.getArgument(1);
|
|
|
|
|
+ assertEquals(started.get().get("generation"), request.get("generation"));
|
|
|
|
|
+ assertEquals(started.get().get("source"), request.get("source"));
|
|
|
|
|
+ return Map.of("generation", request.get("generation"), "status", "STOPPED");
|
|
|
|
|
+ });
|
|
|
|
|
+ JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
|
|
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
|
|
|
|
|
+ .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ new org.springframework.transaction.support.TransactionTemplate(transactions).executeWithoutResult(transaction -> {
|
|
|
|
|
+ try {
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("ACTIVE"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.flv").value("https://media.invalid/prepared.flv"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.secret").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.stream").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.generation").doesNotExist());
|
|
|
|
|
+ action(viewer, "status", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("ACTIVE"));
|
|
|
|
|
+ action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
|
|
+ } catch (Exception failure) { throw new RuntimeException(failure); }
|
|
|
|
|
+ });
|
|
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void failedIdentityRegistrationLeavesNoSessionAndStartsNoMedia() throws Exception {
|
|
|
|
|
+ when(sessions.insert(any(VideoSession.class))).thenReturn(0);
|
|
|
|
|
+ mvc.perform(post(ROOT + "/sessions/prepare")
|
|
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
|
|
|
|
|
+ .andExpect(status().isServiceUnavailable())
|
|
|
|
|
+ .andExpect(jsonPath("$.code").value(503))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("VIDEO_PREPARE_FAILED"));
|
|
|
|
|
+ assertTrue(transactions.rows().isEmpty(), "登记失败不得留下半条会话");
|
|
|
|
|
+ verifyNoInteractions(media);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void anAnonymousViewerJoinsTheLegacyGenerationAndLeavingDoesNotCancelTheSharedStream() throws Exception {
|
|
|
|
|
+ VideoSession legacy = seed("legacy-business-viewer", "ACTIVE", null, "legacy_stream");
|
|
|
|
|
+ legacy.setUserId(7L); java.util.concurrent.atomic.AtomicReference<Map<String, Object>> started = new java.util.concurrent.atomic.AtomicReference<>();
|
|
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
|
|
|
|
|
+ Map<String, Object> request = call.getArgument(1);
|
|
|
|
|
+ started.set(request);
|
|
|
|
|
+ return Map.of("generation", request.get("generation"), "status", "ACTIVE",
|
|
|
|
|
+ "media", Map.of("stream", "legacy_stream", "flv", "https://media.invalid/legacy.flv"));
|
|
|
|
|
+ });
|
|
|
|
|
+ JSONObject viewer = prepare();
|
|
|
|
|
+ String liveBody = action(viewer, "live", viewer.getString("sessionToken"))
|
|
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8);
|
|
|
|
|
+ assertTrue(liveBody.contains("\"status\":\"ACTIVE\""), "live 响应: " + liveBody);
|
|
|
|
|
+ assertNotNull(started.get(), "start 必须被调用一次");
|
|
|
|
|
+ assertEquals("legacy_stream", ((Map<?, ?>) started.get().get("existingMedia")).get("stream"),
|
|
|
|
|
+ "加入既有代次必须带上真实旧句柄,而不是重建");
|
|
|
|
|
+ VideoSession anonymous = transactions.rows().get(viewer.getString("sessionId"));
|
|
|
|
|
+ VideoSession storedLegacy = transactions.rows().get("legacy-business-viewer");
|
|
|
|
|
+ assertNotNull(storedLegacy.getMediaGeneration(), "旧观看者必须被并入一个代次");
|
|
|
|
|
+ assertEquals(storedLegacy.getMediaGeneration(), anonymous.getMediaGeneration(), "匿名观看必须加入同一代次");
|
|
|
|
|
+ assertEquals("legacy_stream", anonymous.getStreamId());
|
|
|
|
|
+
|
|
|
|
|
+ action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
|
|
+ verify(media, never()).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
|
|
+ assertEquals("ACTIVE", transactions.rows().get("legacy-business-viewer").getStatus(),
|
|
|
|
|
+ "还有另一位有效观看者时不得回收共享底流");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void disagreeingLegacyHandlesRefuseTheStartInsteadOfGuessingOne() throws Exception {
|
|
|
|
|
+ seed("legacy-a", "ACTIVE", null, "legacy_stream_a");
|
|
|
|
|
+ seed("legacy-b", "ACTIVE", null, "legacy_stream_b");
|
|
|
|
|
+ JSONObject viewer = prepare();
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("SESSION_HEARTBEAT_FAILED"));
|
|
|
|
|
+ verify(media, never()).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
|
|
+ assertNull(transactions.rows().get(viewer.getString("sessionId")).getMediaGeneration(),
|
|
|
|
|
+ "句柄冲突时不得自行挑一个代次");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void aLegacyActiveViewerWithoutAConfirmedHandleRefusesTheStart() throws Exception {
|
|
|
|
|
+ seed("legacy-no-handle", "ACTIVE", null, null);
|
|
|
|
|
+ JSONObject viewer = prepare();
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable());
|
|
|
|
|
+ verify(media, never()).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test void aSessionFailedByTheProviderCannotBeRevivedByALaterStart() throws Exception {
|
|
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
|
|
|
|
|
+ Map<String, Object> request = call.getArgument(1);
|
|
|
|
|
+ return Map.of("generation", request.get("generation"), "status", "STARTING");
|
|
|
|
|
+ });
|
|
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
|
|
+ Map<String, Object> request = call.getArgument(1);
|
|
|
|
|
+ return Map.of("generation", request.get("generation"), "status", "FAILED");
|
|
|
|
|
+ });
|
|
|
|
|
+ JSONObject viewer = prepare();
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isAccepted());
|
|
|
|
|
+ action(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("FAILED"));
|
|
|
|
|
+ action(viewer, "live", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("FAILED"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media").doesNotExist());
|
|
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 预置一位已有观看者(可来自旧业务用户),用于混合观看与旧句柄场景。 */
|
|
|
|
|
+ private VideoSession seed(String sessionId, String status, String generation, String stream) {
|
|
|
|
|
+ VideoSession row = new VideoSession();
|
|
|
|
|
+ row.setSessionId(sessionId); row.setVideoId(VIDEO); row.setMode("LIVE"); row.setStatus(status);
|
|
|
|
|
+ row.setMediaGeneration(generation); row.setStreamId(stream);
|
|
|
|
|
+ row.setGbDeviceId("34020000002000000001"); row.setGbChannelId("34020000001320000001");
|
|
|
|
|
+ java.time.LocalDateTime now = java.time.LocalDateTime.ofInstant(
|
|
|
|
|
+ java.time.Instant.parse("2026-11-10T08:00:00Z"), java.time.ZoneOffset.UTC);
|
|
|
|
|
+ row.setCreateTime(now); row.setLastSeen(now);
|
|
|
|
|
+ row.setStartDeadline(java.time.LocalDateTime.ofInstant(
|
|
|
|
|
+ java.time.Instant.parse("2026-11-10T08:00:30Z"), java.time.ZoneOffset.UTC));
|
|
|
|
|
+ transactions.rows().put(sessionId, row);
|
|
|
|
|
+ return row;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private JSONObject prepare() throws Exception {
|
|
|
|
|
+ return JSON.parseObject(mvc.perform(post(ROOT + "/sessions/prepare")
|
|
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("deviceCode", CODE))))
|
|
|
|
|
+ .andExpect(status().isCreated()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8))
|
|
|
|
|
+ .getJSONObject("data");
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 以 wrapper 的参数值还原生产查询的过滤条件(video_id、mode、status IN、media_generation、session_id <>)。
|
|
|
|
|
+ * 区分方式:sessionId 是已存在行的主键,代次不是。
|
|
|
|
|
+ */
|
|
|
|
|
+ @SuppressWarnings({ "unchecked", "rawtypes" })
|
|
|
|
|
+ private static Map<String, Object> paramsOf(Object wrapper) {
|
|
|
|
|
+ com.baomidou.mybatisplus.core.conditions.AbstractWrapper raw =
|
|
|
|
|
+ (com.baomidou.mybatisplus.core.conditions.AbstractWrapper) wrapper;
|
|
|
|
|
+ raw.getSqlSegment(); // 先生成片段,MyBatis-Plus 才会填充参数表
|
|
|
|
|
+ return raw.getParamNameValuePairs();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private List<VideoSession> matching(Map<String, Object> parameters) {
|
|
|
|
|
+ Set<Object> params = new HashSet<>(parameters.values());
|
|
|
|
|
+ Set<String> statuses = params.stream()
|
|
|
|
|
+ .filter(value -> value instanceof String && Set.of("STARTING", "ACTIVE", "CLEANUP_PENDING").contains(value))
|
|
|
|
|
+ .map(String.class::cast).collect(Collectors.toSet());
|
|
|
|
|
+ Set<String> uuids = params.stream()
|
|
|
|
|
+ .filter(value -> value instanceof String && UUID_PARAM.matcher((String) value).matches())
|
|
|
|
|
+ .map(String.class::cast).collect(Collectors.toSet());
|
|
|
|
|
+ Set<String> excluded = uuids.stream().filter(transactions.rows()::containsKey).collect(Collectors.toSet());
|
|
|
|
|
+ Set<String> generations = new HashSet<>(uuids);
|
|
|
|
|
+ generations.removeAll(excluded);
|
|
|
|
|
+ List<VideoSession> found = new ArrayList<>();
|
|
|
|
|
+ for (VideoSession row : transactions.rows().values()) {
|
|
|
|
|
+ if (!params.contains(row.getVideoId())) continue;
|
|
|
|
|
+ if (params.contains("LIVE") && !"LIVE".equals(row.getMode())) continue;
|
|
|
|
|
+ if (!statuses.isEmpty() && !statuses.contains(row.getStatus())) continue;
|
|
|
|
|
+ if (excluded.contains(row.getSessionId())) continue;
|
|
|
|
|
+ if (!generations.isEmpty() && !generations.contains(row.getMediaGeneration())) continue;
|
|
|
|
|
+ found.add(row);
|
|
|
|
|
+ }
|
|
|
|
|
+ return found;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private ResultActions action(JSONObject viewer, String action, String token) throws Exception {
|
|
|
|
|
+ return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
|
|
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", token))));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static VideoSession copy(VideoSession source) {
|
|
|
|
|
+ if (source == null) return null;
|
|
|
|
|
+ VideoSession copy = new VideoSession(); BeanUtils.copyProperties(source, copy); return copy;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Configuration
|
|
|
|
|
+ @Import(CockpitVideoControllerTest.HttpConfiguration.class)
|
|
|
|
|
+ static class ConfigurationUnderTest {
|
|
|
|
|
+ @Bean RowTransactions transactionManager() { return new RowTransactions(); }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** Transactional row storage, with no video selection/counting or lifecycle decisions. */
|
|
|
|
|
+ static class RowTransactions extends AbstractPlatformTransactionManager {
|
|
|
|
|
+ private final Map<String, VideoSession> committed = new LinkedHashMap<>();
|
|
|
|
|
+ private final ThreadLocal<Map<String, VideoSession>> originals = new ThreadLocal<>();
|
|
|
|
|
+ private final ThreadLocal<Map<String, VideoSession>> pending = new ThreadLocal<>();
|
|
|
|
|
+ Map<String, VideoSession> rows() { return pending.get() == null ? committed : pending.get(); }
|
|
|
|
|
+ @Override protected Object doGetTransaction() { return new Object(); }
|
|
|
|
|
+ @Override protected boolean isExistingTransaction(Object transaction) { return pending.get() != null; }
|
|
|
|
|
+ @Override protected void doBegin(Object transaction, TransactionDefinition definition) {
|
|
|
|
|
+ Map<String, VideoSession> snapshot = new LinkedHashMap<>();
|
|
|
|
|
+ committed.forEach((id, row) -> snapshot.put(id, copy(row)));
|
|
|
|
|
+ originals.set(new LinkedHashMap<>(snapshot)); pending.set(snapshot);
|
|
|
|
|
+ }
|
|
|
|
|
+ @Override protected void doCommit(DefaultTransactionStatus status) {
|
|
|
|
|
+ // A read-only outer transaction must not overwrite independently committed inner writes.
|
|
|
|
|
+ originals.get().keySet().stream().filter(id -> !pending.get().containsKey(id)).forEach(committed::remove);
|
|
|
|
|
+ pending.get().forEach((id, row) -> {
|
|
|
|
|
+ if (!java.util.Objects.equals(row, originals.get().get(id))) committed.put(id, copy(row));
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+ @Override protected void doRollback(DefaultTransactionStatus status) { }
|
|
|
|
|
+ @Override protected Object doSuspend(Object transaction) {
|
|
|
|
|
+ Object[] state = {pending.get(), originals.get()}; pending.remove(); originals.remove(); return state;
|
|
|
|
|
+ }
|
|
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
|
|
+ @Override protected void doResume(Object transaction, Object suspended) {
|
|
|
|
|
+ Object[] state = (Object[]) suspended;
|
|
|
|
|
+ pending.set((Map<String, VideoSession>) state[0]); originals.set((Map<String, VideoSession>) state[1]);
|
|
|
|
|
+ }
|
|
|
|
|
+ @Override protected void doCleanupAfterCompletion(Object transaction) { pending.remove(); originals.remove(); }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|