Эх сурвалжийг харах

fix(cockpit): share snapshots across app instances

Kazerin 2 сар өмнө
parent
commit
313ce39066

+ 1 - 1
docs/cockpit/README.md

@@ -101,7 +101,7 @@
 
 **跨端点同快照(#69)**:
 
-- 监测点详情接受可选查询参数 `snapshotAt`(ISO-8601 带偏移,语义与 `map-snapshot` 一致)。提供 `snapshotAt` 时,详情与地图通过同一 `CockpitMapSnapshotAdapter` 实例按时间戳复用首次读取的地图快照;相同时间戳不会因两次请求之间的点位/设备关联变化而重新读取,详情 `devices[]` 与 `map-snapshot` 对应点位的 `deviceCodes` 集合一致(含离线设备、不重复、不静默丢失);快照时间戳与请求不一致时返回 `SNAPSHOT_EXPIRED`。该复用范围为单个应用进程生命周期;多实例部署或应用重启需要由共享快照存储/版本化数据源另行提供跨实例一致性。
+- 监测点详情接受可选查询参数 `snapshotAt`(ISO-8601 带偏移,语义与 `map-snapshot` 一致)。提供 `snapshotAt` 时,详情与地图按时间戳复用首次读取的地图快照;相同时间戳不会因两次请求之间的点位/设备关联变化而重新读取,详情 `devices[]` 与 `map-snapshot` 对应点位的 `deviceCodes` 集合一致(含离线设备、不重复、不静默丢失)。快照存于 Redis,保留 10 分钟,应用节点共享;单节点本地最多缓存 256 份以减少 Redis 读取。过期时返回 `SNAPSHOT_EXPIRED`,调用方应刷新快照。
 - 未提供 `snapshotAt` 时走详情适配器路径(尽力模式):两个请求之间点位-设备关系变化时,详情与地图集合可能不一致,前端按决策票 05「跨端点尽力展示并提示可能不一致」处理。
 - **当前正式交付边界**:`equipment_base` 暂无可信坐标校核字段,现网关联设备均按 `UNVERIFIED_COORDINATE` 降级、`renderable=false`,前端准入规则下**只保留设备清单、不绘制设备位置**。可信坐标校核来源(如基于设备安装定位/人工复核的 `coordinateVerified` 字段)需另行排期,由后端在数据源就绪后接入并回填。
 

+ 98 - 0
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/BusinessCockpitMapSnapshotAdapterTest.java

@@ -6,13 +6,17 @@ import com.zksy.base.domain.MonitorPoint;
 import com.zksy.base.service.EquipmentBaseService;
 import com.zksy.base.service.EquipmentTypeService;
 import com.zksy.base.service.MonitorPointService;
+import com.zksy.cockpit.foundation.CockpitSnapshotExpiredException;
 import com.zksy.cockpit.map.BusinessCockpitMapSnapshotAdapter;
 import com.zksy.cockpit.map.CockpitMapSnapshot;
 import com.zksy.cockpit.map.CockpitMapSnapshotService;
 import com.zksy.cockpit.point.BusinessCockpitDeviceFactResolver;
 import com.zksy.cockpit.point.CockpitMonitoringPointDeviceSnapshot;
+import com.zksy.framework.config.FastJson2JsonRedisSerializer;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ValueOperations;
 
 import java.math.BigDecimal;
 import java.time.Clock;
@@ -21,12 +25,16 @@ import java.time.ZoneOffset;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.mock;
@@ -179,6 +187,96 @@ class BusinessCockpitMapSnapshotAdapterTest {
                 "同一 snapshotAt 必须复用首次读取的点位设备关系");
     }
 
+    @Test
+    void mapSnapshotRoundTripsThroughRedisJsonSerializer() {
+        CockpitMapSnapshot snapshot = new CockpitMapSnapshot("2026-09-02T10:00:00+08:00",
+                Collections.emptyList(),
+                Collections.singletonList(new CockpitMapSnapshot.SourceMonitoringPoint(
+                        "POINT-1", "点位一", null, null, null, null, false,
+                        Collections.singletonList(fact("DEVICE-1")))),
+                Collections.emptyList());
+        FastJson2JsonRedisSerializer<Object> serializer = new FastJson2JsonRedisSerializer<>(Object.class);
+
+        Object restored = serializer.deserialize(serializer.serialize(snapshot));
+
+        assertTrue(restored instanceof CockpitMapSnapshot);
+        CockpitMapSnapshot restoredSnapshot = (CockpitMapSnapshot) restored;
+        assertEquals("DEVICE-1", restoredSnapshot.getMonitoringPoints().get(0)
+                .getDevices().get(0).getDeviceCode());
+    }
+
+    @Test
+    void separateAdaptersShareTheFirstSnapshotThroughRedis() {
+        RedisTemplate<Object, Object> sharedRedis = mock(RedisTemplate.class);
+        ValueOperations<Object, Object> values = mock(ValueOperations.class);
+        Map<Object, Object> sharedValues = new ConcurrentHashMap<>();
+        when(sharedRedis.opsForValue()).thenReturn(values);
+        when(values.get(any())).thenAnswer(invocation -> sharedValues.get(invocation.getArgument(0)));
+        when(values.setIfAbsent(any(), any(), anyLong(), eq(java.util.concurrent.TimeUnit.MINUTES)))
+                .thenAnswer(invocation -> sharedValues.putIfAbsent(
+                        invocation.getArgument(0), invocation.getArgument(1)) == null);
+
+        String snapshotAt = "2026-09-02T10:00:00+08:00";
+        MonitorPoint point = point("P-1", "POINT-1", "点位一", null, null);
+        EquipmentBase firstDevice = device("D-1", "DEVICE-1", "设备一", "11", null, null);
+        EquipmentBase changedDevice = device("D-2", "DEVICE-2", "设备二", "11", null, null);
+        stubPoints(Collections.singletonList(point));
+        stubTypes(Collections.singletonList(type(11, "pressure", "压力计", "1")));
+        stubDevices(Collections.singletonList(firstDevice), Collections.singletonList(firstDevice));
+        when(deviceFactResolver.resolve(any(), anyString())).thenAnswer(invocation ->
+                fact(invocation.<EquipmentBase>getArgument(0).getEquipmentCode()));
+        BusinessCockpitMapSnapshotAdapter firstAdapter = new BusinessCockpitMapSnapshotAdapter(
+                monitorPointService, equipmentBaseService, equipmentTypeService, deviceFactResolver,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC), sharedRedis);
+
+        CockpitMapSnapshot first = firstAdapter.load(snapshotAt);
+        stubDevices(Collections.singletonList(changedDevice), Collections.singletonList(changedDevice));
+        BusinessCockpitMapSnapshotAdapter secondAdapter = new BusinessCockpitMapSnapshotAdapter(
+                monitorPointService, equipmentBaseService, equipmentTypeService, deviceFactResolver,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC), sharedRedis);
+        CockpitMapSnapshot second = secondAdapter.load(snapshotAt);
+
+        assertEquals("DEVICE-1", first.getMonitoringPoints().get(0).getDevices().get(0).getDeviceCode());
+        assertEquals("DEVICE-1", second.getMonitoringPoints().get(0).getDevices().get(0).getDeviceCode());
+    }
+
+    @Test
+    void mapPaginationKeepsDeviceCodesFromTheSameSnapshot() {
+        String snapshotAt = "2026-09-02T10:00:00+08:00";
+        MonitorPoint firstPoint = point("P-1", "POINT-1", "点位一", null, null);
+        MonitorPoint secondPoint = point("P-2", "POINT-2", "点位二", null, null);
+        EquipmentBase firstDevice = device("D-1", "DEVICE-1", "设备一", "11", null, null);
+        EquipmentBase secondDevice = device("D-2", "DEVICE-2", "设备二", "11", null, null);
+        stubPoints(Arrays.asList(firstPoint, secondPoint));
+        stubTypes(Collections.singletonList(type(11, "pressure", "压力计", "1")));
+        when(equipmentBaseService.list()).thenReturn(Arrays.asList(firstDevice, secondDevice));
+        when(equipmentBaseService.getEquipmentByPoint("P-1"))
+                .thenReturn(Collections.singletonList(firstDevice));
+        when(equipmentBaseService.getEquipmentByPoint("P-2"))
+                .thenReturn(Collections.singletonList(secondDevice));
+        when(deviceFactResolver.resolve(any(), anyString())).thenAnswer(invocation ->
+                fact(invocation.<EquipmentBase>getArgument(0).getEquipmentCode()));
+        CockpitMapSnapshotService service = new CockpitMapSnapshotService(adapter,
+                Clock.fixed(Instant.parse("2026-09-02T02:00:00Z"), ZoneOffset.UTC));
+
+        service.load("req", 1, 1, snapshotAt, null, null, null);
+        when(equipmentBaseService.getEquipmentByPoint("P-2"))
+                .thenReturn(Collections.singletonList(firstDevice));
+        var secondPage = service.load("req", 2, 1, snapshotAt, null, null, null);
+
+        assertEquals("POINT-2", secondPage.getMonitoringPoints().get(0).getPointCode());
+        assertEquals(Collections.singletonList("DEVICE-2"),
+                secondPage.getMonitoringPoints().get(0).getDeviceCodes());
+    }
+
+    @Test
+    void expiredSnapshotAtIsRejectedInsteadOfLoadingCurrentRelations() {
+        when(monitorPointService.list()).thenReturn(Collections.emptyList());
+
+        assertThrows(CockpitSnapshotExpiredException.class,
+                () -> adapter.load("2026-09-02T09:49:59+08:00"));
+    }
+
     @Test
     void differentSnapshotAtReadsASeparateSourceSnapshot() {
         String firstSnapshotAt = "2026-09-02T10:00:00+08:00";

+ 66 - 4
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/map/BusinessCockpitMapSnapshotAdapter.java

@@ -6,13 +6,18 @@ import com.zksy.base.domain.MonitorPoint;
 import com.zksy.base.service.EquipmentBaseService;
 import com.zksy.base.service.EquipmentTypeService;
 import com.zksy.base.service.MonitorPointService;
+import com.zksy.cockpit.foundation.CockpitSnapshotExpiredException;
 import com.zksy.cockpit.foundation.CockpitTypeIndustry;
 import com.zksy.cockpit.point.BusinessCockpitDeviceFactResolver;
 import com.zksy.cockpit.point.CockpitMonitoringPointDeviceSnapshot;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Primary;
+import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Component;
 
 import java.time.Clock;
+import java.time.Duration;
+import java.time.OffsetDateTime;
 import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
 import java.util.ArrayList;
@@ -24,6 +29,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.stream.Collectors;
@@ -41,8 +47,8 @@ import java.util.stream.Collectors;
  *   <li>类型字典:{@code equipment_type}(行业由 {@code parent_id} 根推导:1 供水、2 排水、3 燃气、4 窨井)。</li>
  * </ul>
  *
- * <p>显式 {@code snapshotAt} 会在适配器进程内固定首次读取结果;地图与详情端点通过同一适配器实例共享该结果,
- * 后续相同时间戳请求不会重新读取变化中的点位关联数据。
+ * <p>显式 {@code snapshotAt} 会固定首次读取结果;地图与详情端点通过共享快照存储复用该版本,
+ * 进程本地缓存只用于减少 Redis 访问,不负责定义跨实例一致性。
  *
  * <p><b>如实接线,不臆造</b>:现网没有「坐标是否已校核」字段,故一律按未校核(
  * {@code coordinateVerified=false})上报,由冻结字典裁决为不可渲染;不为了「图上有东西」而伪造校验状态。
@@ -54,31 +60,87 @@ public class BusinessCockpitMapSnapshotAdapter implements CockpitMapSnapshotAdap
 
     private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
     private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai");
+    private static final Duration SNAPSHOT_RETENTION = Duration.ofMinutes(10);
+    private static final int MAX_CACHED_SNAPSHOTS = 256;
 
     private final MonitorPointService monitorPointService;
     private final EquipmentBaseService equipmentBaseService;
     private final EquipmentTypeService equipmentTypeService;
     private final BusinessCockpitDeviceFactResolver deviceFactResolver;
     private final Clock clock;
+    private final RedisTemplate<Object, Object> redisTemplate;
     private final ConcurrentMap<String, CockpitMapSnapshot> snapshots = new ConcurrentHashMap<>();
 
+    @Autowired
     public BusinessCockpitMapSnapshotAdapter(
             MonitorPointService monitorPointService,
             EquipmentBaseService equipmentBaseService,
             EquipmentTypeService equipmentTypeService,
             BusinessCockpitDeviceFactResolver deviceFactResolver,
-            Clock clock) {
+            Clock clock,
+            RedisTemplate<Object, Object> redisTemplate) {
         this.monitorPointService = monitorPointService;
         this.equipmentBaseService = equipmentBaseService;
         this.equipmentTypeService = equipmentTypeService;
         this.deviceFactResolver = deviceFactResolver;
         this.clock = clock;
+        this.redisTemplate = redisTemplate;
+    }
+
+    public BusinessCockpitMapSnapshotAdapter(
+            MonitorPointService monitorPointService,
+            EquipmentBaseService equipmentBaseService,
+            EquipmentTypeService equipmentTypeService,
+            BusinessCockpitDeviceFactResolver deviceFactResolver,
+            Clock clock) {
+        this(monitorPointService, equipmentBaseService, equipmentTypeService, deviceFactResolver, clock, null);
     }
 
     @Override
     public CockpitMapSnapshot load(String snapshotAt) {
         String resolvedSnapshotAt = snapshotAt == null ? businessTime() : snapshotAt;
-        return snapshots.computeIfAbsent(resolvedSnapshotAt, this::buildSnapshot);
+        OffsetDateTime requestedAt = OffsetDateTime.parse(resolvedSnapshotAt);
+        OffsetDateTime now = OffsetDateTime.now(clock);
+        if (requestedAt.isBefore(now.minus(SNAPSHOT_RETENTION))
+                || requestedAt.isAfter(now.plus(SNAPSHOT_RETENTION))) {
+            throw new CockpitSnapshotExpiredException("snapshot timestamp outside retention window");
+        }
+
+        snapshots.keySet().removeIf(cachedAt ->
+                OffsetDateTime.parse(cachedAt).isBefore(now.minus(SNAPSHOT_RETENTION)));
+        CockpitMapSnapshot cached = snapshots.get(resolvedSnapshotAt);
+        if (cached != null) {
+            return cached;
+        }
+
+        String cacheKey = "cockpit:map-snapshot:" + resolvedSnapshotAt;
+        if (redisTemplate != null) {
+            CockpitMapSnapshot shared = (CockpitMapSnapshot) redisTemplate.opsForValue().get(cacheKey);
+            if (shared != null) {
+                if (snapshots.size() < MAX_CACHED_SNAPSHOTS) {
+                    snapshots.putIfAbsent(resolvedSnapshotAt, shared);
+                }
+                return shared;
+            }
+        }
+        if (snapshots.size() >= MAX_CACHED_SNAPSHOTS) {
+            throw new CockpitSnapshotExpiredException("snapshot cache capacity reached");
+        }
+
+        CockpitMapSnapshot built = buildSnapshot(resolvedSnapshotAt);
+        if (redisTemplate != null) {
+            Boolean stored = redisTemplate.opsForValue()
+                    .setIfAbsent(cacheKey, built, SNAPSHOT_RETENTION.toMinutes(), TimeUnit.MINUTES);
+            if (!Boolean.TRUE.equals(stored)) {
+                CockpitMapSnapshot shared = (CockpitMapSnapshot) redisTemplate.opsForValue().get(cacheKey);
+                if (shared == null) {
+                    throw new CockpitSnapshotExpiredException("snapshot cache unavailable");
+                }
+                built = shared;
+            }
+        }
+        snapshots.putIfAbsent(resolvedSnapshotAt, built);
+        return snapshots.get(resolvedSnapshotAt);
     }
 
     private CockpitMapSnapshot buildSnapshot(String resolvedSnapshotAt) {