|
|
@@ -0,0 +1,595 @@
|
|
|
+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.extension.spring.MybatisSqlSessionFactoryBean;
|
|
|
+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.VideoDeviceService;
|
|
|
+import com.zksy.common.core.domain.entity.SysUser;
|
|
|
+import com.zksy.common.core.domain.model.LoginUser;
|
|
|
+import com.zksy.framework.web.service.TokenService;
|
|
|
+import org.springframework.data.redis.core.RedisTemplate;
|
|
|
+import org.springframework.data.redis.core.ValueOperations;
|
|
|
+import org.springframework.mock.web.MockHttpServletRequest;
|
|
|
+import org.springframework.web.context.request.RequestContextHolder;
|
|
|
+import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
+import java.time.Clock;
|
|
|
+import java.time.Instant;
|
|
|
+import java.time.ZoneId;
|
|
|
+import java.time.ZoneOffset;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.concurrent.TimeUnit;
|
|
|
+import org.apache.ibatis.session.SqlSessionFactory;
|
|
|
+import org.junit.jupiter.api.AfterEach;
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
+import org.junit.jupiter.params.ParameterizedTest;
|
|
|
+import org.junit.jupiter.params.provider.ValueSource;
|
|
|
+import org.junit.jupiter.params.provider.CsvSource;
|
|
|
+import org.mybatis.spring.SqlSessionTemplate;
|
|
|
+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.context.annotation.Primary;
|
|
|
+import org.springframework.core.env.MapPropertySource;
|
|
|
+import org.springframework.http.MediaType;
|
|
|
+import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
|
|
|
+import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
|
|
+import org.springframework.transaction.TransactionSystemException;
|
|
|
+import org.springframework.transaction.support.DefaultTransactionStatus;
|
|
|
+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.annotation.EnableTransactionManagement;
|
|
|
+import org.springframework.transaction.support.TransactionSynchronizationManager;
|
|
|
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
|
|
+
|
|
|
+import javax.servlet.Filter;
|
|
|
+import javax.sql.DataSource;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.UUID;
|
|
|
+import java.util.concurrent.atomic.AtomicReference;
|
|
|
+
|
|
|
+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.*;
|
|
|
+
|
|
|
+/** Real HTTP/security/services, production MyBatis SQL and local in-memory SQL transactions.
|
|
|
+ * No server, application scheduler, external database or device is started. Media is the only
|
|
|
+ * lifecycle boundary substitute; it must never be called with a SQL transaction held.
|
|
|
+ */
|
|
|
+class VideoPreparedSqlTransactionTest {
|
|
|
+ private static final String ROOT = "/api/cockpit/v1/video";
|
|
|
+ private static final String VIDEO = "sql-ledger-id";
|
|
|
+ private static final String CODE = "摄像机/ SQL+01";
|
|
|
+ private AnnotationConfigWebApplicationContext context;
|
|
|
+ private MockMvc mvc;
|
|
|
+ private JdbcTemplate sql;
|
|
|
+ private VideoCollectorClient media;
|
|
|
+ private final AtomicReference<Map<String, Object>> start = new AtomicReference<>();
|
|
|
+ private final AtomicReference<Map<String, Object>> cancel = new AtomicReference<>();
|
|
|
+
|
|
|
+ @BeforeEach void setUp() {
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
+ context = new AnnotationConfigWebApplicationContext();
|
|
|
+ context.setServletContext(new MockServletContext());
|
|
|
+ context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-sql-test", Map.of(
|
|
|
+ "token.header", "Authorization", "token.secret", "offline-sql-contract-not-a-production-secret", "token.expireTime", "60")));
|
|
|
+ context.register(SqlConfiguration.class);
|
|
|
+ context.refresh();
|
|
|
+ sql = new JdbcTemplate(context.getBean(DataSource.class));
|
|
|
+ createSchema(sql);
|
|
|
+ sql.update("INSERT INTO app_user.equipment_base VALUES (?)", VIDEO);
|
|
|
+ mvc = MockMvcBuilders.webAppContextSetup(context)
|
|
|
+ .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
|
|
|
+ EquipmentBase device = new EquipmentBase();
|
|
|
+ device.setEquipmentId(VIDEO); device.setEquipmentCode(CODE); device.setEquipmentName("SQL摄像机"); 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);
|
|
|
+ media = context.getBean(VideoCollectorClient.class);
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ start.set(new LinkedHashMap<>(body));
|
|
|
+ assertTrue(sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE status='STARTING' AND media_generation=?",
|
|
|
+ Long.class, body.get("generation")) > 0, "intent must really commit before media starts");
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media",
|
|
|
+ Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
|
|
|
+ });
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/status"), any())).thenAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media",
|
|
|
+ Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
|
|
|
+ });
|
|
|
+ when(media.get(eq("/api/play/start/34020000002000000001/34020000001320000001"), any()))
|
|
|
+ .thenReturn(Map.of("stream", "sql_stream", "mediaServerId", "node-sql", "flv", "https://media.invalid/sql.flv"));
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STOPPED");
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ @AfterEach void close() {
|
|
|
+ if (context != null) context.close();
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void activeSqlFailureCompensatesTheAlreadyStartedGenerationBeforeReturning() throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ // This is a real failed SQL statement AFTER identity/STARTING commit and AFTER media start.
|
|
|
+ sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_active CHECK (status <> 'ACTIVE')");
|
|
|
+ action(viewer, "live").andExpect(status().isServiceUnavailable())
|
|
|
+ .andExpect(jsonPath("$.data.media").doesNotExist());
|
|
|
+ assertNotNull(start.get(), "the test must actually start media before the injected failure");
|
|
|
+ assertNotNull(cancel.get(), "ACTIVE persistence failure must immediately compensate, not leave a STARTING orphan");
|
|
|
+ assertEquals(start.get().get("generation"), cancel.get().get("generation"));
|
|
|
+ assertEquals(start.get().get("source"), cancel.get().get("source"));
|
|
|
+ assertEquals(start.get().get("startDeadline"), cancel.get().get("startDeadline"));
|
|
|
+ action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @ParameterizedTest
|
|
|
+ @ValueSource(booleans = {false, true})
|
|
|
+ void activeCommitFailureOrLostAcknowledgementCompensatesExactlyThisGeneration(boolean committed) throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ CommitFaultTransactions transactions = context.getBean(CommitFaultTransactions.class);
|
|
|
+ transactions.failActiveCommit = true;
|
|
|
+ transactions.commitBeforeFailure = committed;
|
|
|
+ action(viewer, "live").andExpect(status().isServiceUnavailable());
|
|
|
+ assertTrue(transactions.failureInjected, "must fail ACTIVE commit, not prepare or intent commit");
|
|
|
+ assertNotNull(cancel.get(), "commit failure after media creation must compensate immediately");
|
|
|
+ assertEquals(start.get().get("generation"), cancel.get().get("generation"));
|
|
|
+ action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void failedCompensationRemainsPendingAndCanBeReclaimedWithoutASecondStart() throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_active CHECK (status <> 'ACTIVE')");
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
|
|
|
+ throw new IllegalStateException("offline media boundary failure");
|
|
|
+ });
|
|
|
+ action(viewer, "live").andExpect(status().isServiceUnavailable());
|
|
|
+ assertNotNull(cancel.get(), "failed SQL must trigger compensation even when cancel also fails");
|
|
|
+ action(viewer, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("CLEANUP_PENDING"))
|
|
|
+ .andExpect(jsonPath("$.data.media").doesNotExist());
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ assertEquals(start.get().get("generation"), body.get("generation"));
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STOPPED");
|
|
|
+ });
|
|
|
+ action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @ParameterizedTest
|
|
|
+ @ValueSource(booleans = {false, true})
|
|
|
+ void oldUserAndPreparedAnonymousReleaseOnlyTheLastSharedGeneration(boolean oldUserLast) throws Exception {
|
|
|
+ String bearer = userToken(7);
|
|
|
+ JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
|
|
|
+ .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ action(viewer, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ACTIVE"));
|
|
|
+ assertEquals("sql_stream", ((Map<?, ?>) start.get().get("existingMedia")).get("stream"));
|
|
|
+ mvc.perform(post("/api/video/sessions/{id}/stop", legacy.getString("sessionId"))
|
|
|
+ .header("Authorization", userToken(8))).andExpect(jsonPath("$.code").value(500));
|
|
|
+ assertNull(cancel.get(), "wrong ownership cannot release any media");
|
|
|
+ if (oldUserLast) {
|
|
|
+ action(viewer, "stop").andExpect(status().isOk());
|
|
|
+ assertNull(cancel.get(), "one remaining user still owns this generation");
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ } else {
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ assertNull(cancel.get(), "one remaining anonymous viewer still owns this generation");
|
|
|
+ action(viewer, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
|
|
|
+ action(viewer, "stop").andExpect(status().isOk());
|
|
|
+ }
|
|
|
+ assertNotNull(cancel.get());
|
|
|
+ assertEquals(start.get().get("generation"), cancel.get().get("generation"));
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ action(viewer, "stop").andExpect(status().isOk());
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
+ verify(media, never()).get(eq("/api/play/stop/34020000002000000001/34020000001320000001"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @ParameterizedTest
|
|
|
+ @ValueSource(strings = {"PREPARED", "STARTING", "CLEANUP_PENDING"})
|
|
|
+ void expiryReclaimsEveryNonterminalIntentWithoutAnHttpPoll(String initial) throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ if (!"PREPARED".equals(initial)) {
|
|
|
+ if ("STARTING".equals(initial)) when(media.post(eq("/internal/video/lifecycle/start"), any())).thenAnswer(call -> {
|
|
|
+ Map<String, Object> body = call.getArgument(1); start.set(new LinkedHashMap<>(body));
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STARTING");
|
|
|
+ });
|
|
|
+ action(viewer, "live");
|
|
|
+ if ("CLEANUP_PENDING".equals(initial)) {
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "CLEANUP_PENDING");
|
|
|
+ });
|
|
|
+ action(viewer, "stop").andExpect(status().isAccepted());
|
|
|
+ when(media.post(eq("/internal/video/lifecycle/cancel"), any())).thenAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STOPPED");
|
|
|
+ });
|
|
|
+ }
|
|
|
+ }
|
|
|
+ context.getBean(MutableClock.class).advance("PREPARED".equals(initial) ? 121 : 31);
|
|
|
+ context.getBean(VideoDeviceService.class).expireSessions();
|
|
|
+ // Read persisted outcome before status (which is itself allowed to perform cleanup).
|
|
|
+ assertEquals("STOPPED", sql.queryForObject("SELECT status FROM app_user.video_play_session WHERE session_id=?",
|
|
|
+ String.class, viewer.getString("sessionId")));
|
|
|
+ action(viewer, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ if ("PREPARED".equals(initial)) verifyNoInteractions(media);
|
|
|
+ else assertEquals(start.get().get("generation"), cancel.get().get("generation"));
|
|
|
+ }
|
|
|
+
|
|
|
+ @ParameterizedTest
|
|
|
+ @CsvSource({"STARTING,false", "UNKNOWN,false", "STARTING,true", "UNKNOWN,true"})
|
|
|
+ void joiningAHealthyGenerationSurvivesItsOldDeadlineUntilTheActivePeerLeaves(String outcome, boolean peerExpires) throws Exception {
|
|
|
+ JSONObject active = prepare();
|
|
|
+ action(active, "live").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("ACTIVE"));
|
|
|
+ Map<String, Object> original = new LinkedHashMap<>(start.get());
|
|
|
+ MutableClock clock = context.getBean(MutableClock.class);
|
|
|
+ clock.advance(31);
|
|
|
+ action(active, "heartbeat").andExpect(status().isOk());
|
|
|
+ JSONObject joining = prepare();
|
|
|
+ doAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ assertEquals(original.get("generation"), body.get("generation"));
|
|
|
+ assertEquals(original.get("startDeadline"), body.get("startDeadline"));
|
|
|
+ if ("UNKNOWN".equals(outcome)) throw new IllegalStateException("offline lost start acknowledgement");
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STARTING");
|
|
|
+ }).when(media).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
+ doAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STARTING");
|
|
|
+ }).when(media).post(eq("/internal/video/lifecycle/status"), any());
|
|
|
+ action(joining, "live").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
|
|
|
+ action(joining, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
|
|
|
+ context.getBean(VideoDeviceService.class).expireSessions();
|
|
|
+ action(joining, "status").andExpect(status().isAccepted()).andExpect(jsonPath("$.data.status").value("STARTING"));
|
|
|
+ assertNull(cancel.get(), "neither status nor the expiry worker may kill a healthy generation's joining viewer");
|
|
|
+ if (peerExpires) clock.advance(121);
|
|
|
+ else action(active, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ context.getBean(VideoDeviceService.class).expireSessions();
|
|
|
+ action(joining, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ assertNotNull(cancel.get(), "without a healthy peer the original expired deadline must reclaim the join");
|
|
|
+ assertEquals(original.get("generation"), cancel.get().get("generation"));
|
|
|
+ assertEquals(original.get("startDeadline"), cancel.get().get("startDeadline"));
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void aHealthyPeerDoesNotKeepAnAbandonedJoiningIntentForever() throws Exception {
|
|
|
+ JSONObject active = prepare();
|
|
|
+ action(active, "live").andExpect(status().isOk());
|
|
|
+ Object generation = start.get().get("generation");
|
|
|
+ MutableClock clock = context.getBean(MutableClock.class);
|
|
|
+ clock.advance(31);
|
|
|
+ action(active, "heartbeat").andExpect(status().isOk());
|
|
|
+ JSONObject joining = prepare();
|
|
|
+ doThrow(new IllegalStateException("offline start acknowledgement lost"))
|
|
|
+ .when(media).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
+ action(joining, "live").andExpect(status().isAccepted());
|
|
|
+ clock.advance(119);
|
|
|
+ action(active, "heartbeat").andExpect(status().isOk());
|
|
|
+ clock.advance(2);
|
|
|
+ context.getBean(VideoDeviceService.class).expireSessions();
|
|
|
+ // An abandoned viewer's own lease is bounded even while another viewer renews forever.
|
|
|
+ action(joining, "status").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ assertNull(cancel.get(), "expiring the abandoned join must not cancel its healthy peer");
|
|
|
+ action(active, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
|
|
|
+ action(active, "stop").andExpect(status().isOk());
|
|
|
+ assertEquals(generation, cancel.get().get("generation"));
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void legacyAnonymousStopReadsBackTheCommittedStoppedState() throws Exception {
|
|
|
+ JSONObject viewer = JSON.parseObject(mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON)
|
|
|
+ .content(JSON.toJSONString(Map.of("deviceCode", CODE))))
|
|
|
+ .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
+ action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ verify(media, times(1)).get(eq("/api/play/stop/34020000002000000001/34020000001320000001"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void anOldApiViewerJoiningAnExistingPreparedGenerationNeverUsesBlindStart() throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ action(viewer, "live").andExpect(status().isOk());
|
|
|
+ String generation = (String) start.get().get("generation");
|
|
|
+ Object originalDeadline = start.get().get("startDeadline");
|
|
|
+ context.getBean(MutableClock.class).advance(31);
|
|
|
+ String bearer = userToken(7);
|
|
|
+ JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
|
|
|
+ .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
|
|
|
+ .andExpect(jsonPath("$.data.flv").value("https://media.invalid/sql.flv"))
|
|
|
+ .andExpect(jsonPath("$.data.generation").doesNotExist())
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
+ assertEquals(generation, start.get().get("generation"));
|
|
|
+ assertEquals(originalDeadline, start.get().get("startDeadline"), "joining must not extend a generation's start deadline");
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ assertNull(cancel.get());
|
|
|
+ action(viewer, "stop").andExpect(status().isOk());
|
|
|
+ assertEquals(generation, cancel.get().get("generation"));
|
|
|
+ verify(media, never()).get(startsWith("/api/play/start/"), any());
|
|
|
+ verify(media, never()).get(startsWith("/api/play/stop/"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void sqlFailureWhileJoiningDoesNotCancelTheOtherActiveViewer() throws Exception {
|
|
|
+ String bearer = userToken(7);
|
|
|
+ JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
|
|
|
+ .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ String rejectedId = viewer.getString("sessionId");
|
|
|
+ assertNotNull(UUID.fromString(rejectedId));
|
|
|
+ sql.execute("ALTER TABLE app_user.video_play_session ADD CONSTRAINT reject_join CHECK (status <> 'ACTIVE' OR session_id <> '"
|
|
|
+ + rejectedId + "')");
|
|
|
+ action(viewer, "live").andExpect(status().isServiceUnavailable());
|
|
|
+ action(viewer, "status").andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ assertNull(cancel.get(), "a failed joining viewer must not cancel the existing user's generation");
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ assertNotNull(cancel.get());
|
|
|
+ verify(media, never()).get(startsWith("/api/play/stop/"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void unrelatedVideoModeAndGenerationDoNotCountAsOwnersOfThisGeneration() throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ action(viewer, "live").andExpect(status().isOk());
|
|
|
+ String generation = (String) start.get().get("generation");
|
|
|
+ // Adversarial persisted rows: the actual SQL must filter on all three dimensions.
|
|
|
+ seedOtherOwner(VIDEO, "PLAYBACK", generation);
|
|
|
+ seedOtherOwner("another-video", "LIVE", generation);
|
|
|
+ seedOtherOwner(VIDEO, "LIVE", UUID.randomUUID().toString());
|
|
|
+ action(viewer, "stop").andExpect(status().isOk()).andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
+ assertNotNull(cancel.get(), "unrelated owners must not suppress last-viewer reclamation");
|
|
|
+ assertEquals(generation, cancel.get().get("generation"));
|
|
|
+ assertEquals(3L, sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE status='ACTIVE'", Long.class));
|
|
|
+ }
|
|
|
+
|
|
|
+ private void seedOtherOwner(String videoId, String mode, String generation) {
|
|
|
+ sql.update("INSERT INTO app_user.video_play_session (session_id,video_id,user_id,mode,status,media_generation,create_time,last_seen) "
|
|
|
+ + "VALUES (?,?,7,?,'ACTIVE',?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)", UUID.randomUUID().toString(),videoId,mode,generation);
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void liveHeartbeatsKeepANonexpiredViewerOutOfTheExpiryScan() throws Exception {
|
|
|
+ JSONObject viewer = prepare();
|
|
|
+ action(viewer, "live").andExpect(status().isOk());
|
|
|
+ context.getBean(MutableClock.class).advance(119);
|
|
|
+ action(viewer, "heartbeat").andExpect(status().isOk());
|
|
|
+ context.getBean(MutableClock.class).advance(2);
|
|
|
+ context.getBean(VideoDeviceService.class).expireSessions();
|
|
|
+ action(viewer, "status").andExpect(jsonPath("$.data.status").value("ACTIVE"));
|
|
|
+ assertNull(cancel.get());
|
|
|
+ }
|
|
|
+
|
|
|
+ @ParameterizedTest
|
|
|
+ @ValueSource(booleans = {true, false})
|
|
|
+ void oldManualStopRetainsOnlyTheKnownOriginAndNeverAcknowledgesUnknownCleanup(boolean knownNode) throws Exception {
|
|
|
+ VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
|
|
|
+ binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/old-camera");
|
|
|
+ Map<String, Object> legacyMedia = new LinkedHashMap<>(Map.of("stream", "old_manual_stream",
|
|
|
+ "proxyKey", "old-private-key", "flv", "https://media.invalid/old.flv"));
|
|
|
+ if (knownNode) legacyMedia.put("mediaServerId", "origin-not-default");
|
|
|
+ when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(legacyMedia);
|
|
|
+ String bearer = userToken(7);
|
|
|
+ JSONObject legacy = JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO)
|
|
|
+ .header("Authorization", bearer)).andExpect(jsonPath("$.code").value(200))
|
|
|
+ .andExpect(jsonPath("$.data.flv").value("https://media.invalid/old.flv"))
|
|
|
+ .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
|
|
|
+ .andExpect(jsonPath("$.data.mediaServerId").doesNotExist())
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
+ AtomicReference<Map<String, Object>> stopBody = new AtomicReference<>();
|
|
|
+ doAnswer(call -> {
|
|
|
+ stopBody.set(new LinkedHashMap<>(call.getArgument(1)));
|
|
|
+ // The external client reports pending/transport-unknown as failure, not confirmed stop.
|
|
|
+ throw new com.zksy.common.exception.ServiceException("offline provider cleanup pending after restart");
|
|
|
+ }).when(media).post(eq("/internal/video/manual/stop"), any());
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(500));
|
|
|
+ Map<String, Object> expected = knownNode ? Map.of("mediaServerId", "origin-not-default", "key", "old-private-key")
|
|
|
+ : Map.of("key", "old-private-key");
|
|
|
+ assertEquals(expected, stopBody.get(), "SQL's source node must survive provider restart; an unknown node must never be invented");
|
|
|
+ doAnswer(call -> {
|
|
|
+ assertEquals(expected, call.getArgument(1));
|
|
|
+ return null; // The existing successful manual-stop envelope has no data.
|
|
|
+ }).when(media).post(eq("/internal/video/manual/stop"), any());
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ oldStop(legacy, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ verify(media, times(2)).post(eq("/internal/video/manual/stop"), any());
|
|
|
+ verify(media, never()).post(startsWith("/internal/video/lifecycle/"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void twoOldManualUsersAdoptOneKnownHandleAndOnlyTheLastUserCancels() throws Exception {
|
|
|
+ VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
|
|
|
+ binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/shared-old-camera");
|
|
|
+ Map<String, Object> knownMedia = Map.of("stream", "shared_old_stream", "mediaServerId", "origin-old-node",
|
|
|
+ "proxyKey", "shared-private-key", "flv", "https://media.invalid/shared-old.flv");
|
|
|
+ when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(knownMedia);
|
|
|
+ doAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1); start.set(new LinkedHashMap<>(body));
|
|
|
+ assertEquals(Map.of("stream", "shared_old_stream", "mediaServerId", "origin-old-node", "proxyKey", "shared-private-key"),
|
|
|
+ body.get("existingMedia"), "adoption must be bound to the persisted physical handle");
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "ACTIVE", "media", knownMedia);
|
|
|
+ }).when(media).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
+ String firstBearer = userToken(7), secondBearer = userToken(8);
|
|
|
+ JSONObject first = oldManualStart(firstBearer);
|
|
|
+ assertNull(start.get(), "the very first old LIVE request retains its legacy start contract");
|
|
|
+ JSONObject second = oldManualStart(secondBearer);
|
|
|
+ assertNotNull(start.get(), "the second old user must coordinate adoption instead of starting another proxy");
|
|
|
+ String generation = (String) start.get().get("generation");
|
|
|
+ assertEquals(2L, sql.queryForObject("SELECT COUNT(*) FROM app_user.video_play_session WHERE mode='LIVE' AND status='ACTIVE' AND media_generation=?",
|
|
|
+ Long.class, generation));
|
|
|
+ oldStop(first, secondBearer).andExpect(jsonPath("$.code").value(500));
|
|
|
+ assertNull(cancel.get());
|
|
|
+ oldStop(first, firstBearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ assertNull(cancel.get(), "the second old viewer still owns the adopted handle");
|
|
|
+ doAnswer(call -> {
|
|
|
+ assertFalse(TransactionSynchronizationManager.isActualTransactionActive());
|
|
|
+ Map<String, Object> body = call.getArgument(1); cancel.set(new LinkedHashMap<>(body));
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "CLEANUP_PENDING");
|
|
|
+ }).when(media).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
+ oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(500));
|
|
|
+ assertEquals(generation, cancel.get().get("generation"));
|
|
|
+ assertEquals(start.get().get("existingMedia"), cancel.get().get("existingMedia"));
|
|
|
+ doAnswer(call -> {
|
|
|
+ Map<String, Object> body = call.getArgument(1);
|
|
|
+ assertEquals(generation, body.get("generation"));
|
|
|
+ return Map.of("generation", body.get("generation"), "status", "STOPPED");
|
|
|
+ }).when(media).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
+ oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ oldStop(second, secondBearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/manual/start"), any());
|
|
|
+ verify(media, times(1)).post(eq("/internal/video/lifecycle/start"), any());
|
|
|
+ verify(media, times(2)).post(eq("/internal/video/lifecycle/cancel"), any());
|
|
|
+ verify(media, never()).post(eq("/internal/video/manual/stop"), any());
|
|
|
+ }
|
|
|
+
|
|
|
+ @Test void anUnknownLegacyManualNodeCannotBeGuessedOrBlindlyRestartedForAnotherOldUser() throws Exception {
|
|
|
+ VideoDeviceRecord binding = context.getBean(EquipmentVideoBindingMapper.class).find(VIDEO);
|
|
|
+ binding.setSourceType("MANUAL"); binding.setVideoUrl("rtsp://offline.invalid/unknown-node-camera");
|
|
|
+ when(media.post(eq("/internal/video/manual/start"), any())).thenReturn(Map.of("stream", "shared_old_stream",
|
|
|
+ "proxyKey", "shared-private-key", "flv", "https://media.invalid/shared-old.flv"));
|
|
|
+ String bearer = userToken(7);
|
|
|
+ JSONObject first = oldManualStart(bearer);
|
|
|
+ clearInvocations(media);
|
|
|
+ mvc.perform(post("/api/video/devices/{id}/live", VIDEO).header("Authorization", userToken(8)))
|
|
|
+ .andExpect(jsonPath("$.code").value(500));
|
|
|
+ verifyNoInteractions(media); // No guessed default node, adoption or second legacy start.
|
|
|
+ oldStop(first, bearer).andExpect(jsonPath("$.code").value(200));
|
|
|
+ verify(media).post("/internal/video/manual/stop", Map.of("key", "shared-private-key"));
|
|
|
+ }
|
|
|
+
|
|
|
+ private JSONObject oldManualStart(String bearer) throws Exception {
|
|
|
+ return JSON.parseObject(mvc.perform(post("/api/video/devices/{id}/live", VIDEO).header("Authorization", bearer))
|
|
|
+ .andExpect(jsonPath("$.code").value(200))
|
|
|
+ .andExpect(jsonPath("$.data.flv").value("https://media.invalid/shared-old.flv"))
|
|
|
+ .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
|
|
|
+ .andExpect(jsonPath("$.data.mediaServerId").doesNotExist())
|
|
|
+ .andExpect(jsonPath("$.data.generation").doesNotExist())
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
+ }
|
|
|
+
|
|
|
+ private ResultActions oldStop(JSONObject viewer, String bearer) throws Exception {
|
|
|
+ return mvc.perform(post("/api/video/sessions/{id}/stop", viewer.getString("sessionId")).header("Authorization", bearer));
|
|
|
+ }
|
|
|
+
|
|
|
+ private String userToken(long id) {
|
|
|
+ SysUser user = new SysUser(); user.setUserId(id); user.setUserName("sql-viewer-" + id);
|
|
|
+ LoginUser login = new LoginUser(id, 101L, user, Set.of("video:device:play"));
|
|
|
+ MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("127.0.0.1");
|
|
|
+ ServletRequestAttributes attributes = new ServletRequestAttributes(request);
|
|
|
+ RequestContextHolder.setRequestAttributes(attributes);
|
|
|
+ try { return "Bearer " + context.getBean(TokenService.class).createToken(login); }
|
|
|
+ finally { attributes.requestCompleted(); RequestContextHolder.resetRequestAttributes(); }
|
|
|
+ }
|
|
|
+
|
|
|
+ static void createSchema(JdbcTemplate sql) {
|
|
|
+ sql.execute("CREATE SCHEMA app_user");
|
|
|
+ sql.execute("CREATE TABLE app_user.equipment_base (equipment_id varchar(64) PRIMARY KEY)");
|
|
|
+ sql.execute("CREATE TABLE app_user.video_play_session (session_id varchar(36) PRIMARY KEY, "
|
|
|
+ + "video_id varchar(64) NOT NULL, user_id bigint, anonymous_token_hash varchar(43), "
|
|
|
+ + "mode varchar(16) NOT NULL, status varchar(16) NOT NULL, stream_id varchar(200), proxy_key varchar(300), "
|
|
|
+ + "gb_device_id varchar(20), gb_channel_id varchar(20), media_generation varchar(64), media_server_id varchar(64), start_deadline timestamp, "
|
|
|
+ + "create_time timestamp NOT NULL, last_seen timestamp NOT NULL, end_time timestamp)");
|
|
|
+ }
|
|
|
+
|
|
|
+ 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");
|
|
|
+ }
|
|
|
+
|
|
|
+ private ResultActions action(JSONObject viewer, String action) throws Exception {
|
|
|
+ return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", viewer.getString("sessionToken")))));
|
|
|
+ }
|
|
|
+
|
|
|
+ /** Injects only the external commit outcome; all statements/rollback/normal commits are real JDBC. */
|
|
|
+ static class CommitFaultTransactions extends DataSourceTransactionManager {
|
|
|
+ boolean failActiveCommit;
|
|
|
+ boolean commitBeforeFailure;
|
|
|
+ boolean failureInjected;
|
|
|
+ CommitFaultTransactions(DataSource ds) { super(ds); setRollbackOnCommitFailure(true); }
|
|
|
+ @Override protected void doCommit(DefaultTransactionStatus status) {
|
|
|
+ if (failActiveCommit && new JdbcTemplate(getDataSource()).queryForObject(
|
|
|
+ "SELECT COUNT(*) FROM app_user.video_play_session WHERE status='ACTIVE'", Long.class) > 0) {
|
|
|
+ failActiveCommit = false;
|
|
|
+ failureInjected = true;
|
|
|
+ if (commitBeforeFailure) super.doCommit(status);
|
|
|
+ throw new TransactionSystemException("offline injected ACTIVE commit failure");
|
|
|
+ }
|
|
|
+ super.doCommit(status);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static class MutableClock extends Clock {
|
|
|
+ private Instant now = Instant.parse("2026-11-10T08:00:00Z");
|
|
|
+ void advance(long seconds) { now = now.plusSeconds(seconds); }
|
|
|
+ @Override public Instant instant() { return now; }
|
|
|
+ @Override public ZoneId getZone() { return ZoneOffset.UTC; }
|
|
|
+ @Override public Clock withZone(ZoneId zone) { return Clock.fixed(now, zone); }
|
|
|
+ }
|
|
|
+
|
|
|
+ @Configuration
|
|
|
+ @EnableTransactionManagement
|
|
|
+ @Import(CockpitVideoControllerTest.HttpConfiguration.class)
|
|
|
+ static class SqlConfiguration {
|
|
|
+ @Bean @Primary MutableClock sqlClock() { return new MutableClock(); }
|
|
|
+ @Bean @Primary @SuppressWarnings("unchecked") RedisTemplate<String, Object> sqlRedis() {
|
|
|
+ Map<String, Object> values = new HashMap<>();
|
|
|
+ RedisTemplate<String, Object> redis = mock(RedisTemplate.class);
|
|
|
+ ValueOperations<String, Object> operations = mock(ValueOperations.class);
|
|
|
+ when(redis.opsForValue()).thenReturn(operations);
|
|
|
+ when(operations.get(anyString())).thenAnswer(call -> values.get(call.getArgument(0)));
|
|
|
+ doAnswer(call -> { values.put(call.getArgument(0), call.getArgument(1)); return null; })
|
|
|
+ .when(operations).set(anyString(), any(), anyLong(), any(TimeUnit.class));
|
|
|
+ return redis;
|
|
|
+ }
|
|
|
+ @Bean DataSource dataSource() {
|
|
|
+ DriverManagerDataSource ds = new DriverManagerDataSource();
|
|
|
+ ds.setDriverClassName("org.h2.Driver");
|
|
|
+ ds.setUrl("jdbc:h2:mem:video_" + UUID.randomUUID() + ";MODE=PostgreSQL;DB_CLOSE_DELAY=-1");
|
|
|
+ ds.setUsername("sa"); ds.setPassword(""); return ds;
|
|
|
+ }
|
|
|
+ @Bean CommitFaultTransactions transactionManager(DataSource ds) { return new CommitFaultTransactions(ds); }
|
|
|
+ @Bean @Primary VideoSessionMapper sqlSessions(DataSource ds) throws Exception {
|
|
|
+ MybatisConfiguration config = new MybatisConfiguration();
|
|
|
+ config.setMapUnderscoreToCamelCase(true);
|
|
|
+ config.addMapper(VideoSessionMapper.class);
|
|
|
+ MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
|
|
|
+ factory.setDataSource(ds); factory.setConfiguration(config);
|
|
|
+ SqlSessionFactory built = factory.getObject();
|
|
|
+ return new SqlSessionTemplate(built).getMapper(VideoSessionMapper.class);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|