Explorar el Código

fix(cockpit): reuse map snapshot for point detail

Kazerin hace 2 meses
padre
commit
bbcfa52036

+ 1 - 1
docs/cockpit/README.md

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

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

@@ -146,7 +146,59 @@ class BusinessCockpitMapSnapshotAdapterTest {
                 "窨井根映射为 MANHOLE 传值,交由服务层判非正式行业,而非在适配器吞掉");
     }
 
-    // ---- stubbing helpers ----
+    @Test
+    void sameSnapshotAtReusesTheFirstSourceSnapshotAfterRelationsChange() {
+        String snapshotAt = "2026-09-02T10:00:00+08:00";
+        MonitorPoint point = point("P-1", "POINT-1", "点位一", new BigDecimal("110.4"), new BigDecimal("28.4"));
+        EquipmentType equipmentType = type(11, "pressure", "压力计", "1");
+        EquipmentBase firstDevice = device("D-1", "DEVICE-1", "设备一", "11",
+                new BigDecimal("110.401"), new BigDecimal("28.401"));
+        EquipmentBase secondDevice = device("D-2", "DEVICE-2", "设备二", "11",
+                new BigDecimal("110.402"), new BigDecimal("28.402"));
+        stubPoints(Collections.singletonList(point));
+        stubTypes(Collections.singletonList(equipmentType));
+        stubDevices(Collections.singletonList(firstDevice), Collections.singletonList(firstDevice));
+        when(deviceFactResolver.resolve(any(), anyString())).thenAnswer(invocation -> {
+            EquipmentBase device = invocation.getArgument(0);
+            return fact(device.getEquipmentCode());
+        });
+
+        CockpitMapSnapshot first = adapter.load(snapshotAt);
+
+        stubDevices(Collections.singletonList(secondDevice), Collections.singletonList(secondDevice));
+        CockpitMapSnapshot second = adapter.load(snapshotAt);
+
+        assertEquals(Collections.singletonList("DEVICE-1"),
+                first.getMonitoringPoints().get(0).getDevices().stream()
+                        .map(CockpitMonitoringPointDeviceSnapshot::getDeviceCode)
+                        .collect(java.util.stream.Collectors.toList()));
+        assertEquals(Collections.singletonList("DEVICE-1"),
+                second.getMonitoringPoints().get(0).getDevices().stream()
+                        .map(CockpitMonitoringPointDeviceSnapshot::getDeviceCode)
+                        .collect(java.util.stream.Collectors.toList()),
+                "同一 snapshotAt 必须复用首次读取的点位设备关系");
+    }
+
+    @Test
+    void differentSnapshotAtReadsASeparateSourceSnapshot() {
+        String firstSnapshotAt = "2026-09-02T10:00:00+08:00";
+        String secondSnapshotAt = "2026-09-02T10:01:00+08:00";
+        MonitorPoint point = point("P-1", "POINT-1", "点位一", new BigDecimal("110.4"), new BigDecimal("28.4"));
+        stubPoints(Collections.singletonList(point));
+        stubTypes(Collections.singletonList(type(11, "pressure", "压力计", "1")));
+        EquipmentBase firstDevice = device("D-1", "DEVICE-1", "设备一", "11", null, null);
+        EquipmentBase secondDevice = device("D-2", "DEVICE-2", "设备二", "11", null, null);
+        stubDevices(Collections.singletonList(firstDevice), Collections.singletonList(firstDevice));
+        when(deviceFactResolver.resolve(any(), anyString())).thenAnswer(invocation ->
+                fact(invocation.<EquipmentBase>getArgument(0).getEquipmentCode()));
+
+        CockpitMapSnapshot first = adapter.load(firstSnapshotAt);
+        stubDevices(Collections.singletonList(secondDevice), Collections.singletonList(secondDevice));
+        CockpitMapSnapshot second = adapter.load(secondSnapshotAt);
+
+        assertEquals("DEVICE-1", first.getMonitoringPoints().get(0).getDevices().get(0).getDeviceCode());
+        assertEquals("DEVICE-2", second.getMonitoringPoints().get(0).getDevices().get(0).getDeviceCode());
+    }
 
     private void stubPoints(List<MonitorPoint> points) {
         when(monitorPointService.list()).thenReturn(points);

+ 29 - 1
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitMonitoringPointDetailControllerTest.java

@@ -236,7 +236,7 @@ class CockpitMonitoringPointDetailControllerTest {
         verifyNoInteractions(adapter);
     }
 
-        @Test
+    @Test
     void detailWithMalformedSnapshotAtReturnsInvalidRequest() throws Exception {
         mockMvc.perform(get("/api/cockpit/v1/monitoring-points/MP-SNAP")
                         .param("snapshotAt", "not-a-timestamp"))
@@ -244,11 +244,39 @@ class CockpitMonitoringPointDetailControllerTest {
                 .andExpect(jsonPath("$.code").value(400))
                 .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
                 .andExpect(jsonPath("$.data.message").value("监测点快照参数不合法"));
+    }
+
+    @Test
+    void detailWithBlankSnapshotAtReturnsInvalidRequest() throws Exception {
+        mockMvc.perform(get("/api/cockpit/v1/monitoring-points/MP-SNAP")
+                        .param("snapshotAt", ""))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.code").value(400))
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.message").value("监测点快照参数不合法"));
 
         verifyNoInteractions(adapter);
         verifyNoInteractions(mapAdapter);
     }
 
+    @Test
+    void detailSnapshotNormalizesDeviceCodeBeforeReturningCards() throws Exception {
+        CockpitMapSnapshot snapshot = new CockpitMapSnapshot(
+                "2026-09-02T10:00:00+08:00", Collections.emptyList(),
+                Collections.singletonList(new CockpitMapSnapshot.SourceMonitoringPoint(
+                        "MP-SNAP", "供水干管监测点", null, "11",
+                        new BigDecimal("110.141"), new BigDecimal("28.452"), false,
+                        Collections.singletonList(
+                                device(" EQ-001 ", true, false, false, true, Collections.emptyList())))),
+                Collections.emptyList());
+        when(mapAdapter.load("2026-09-02T10:00:00+08:00")).thenReturn(snapshot);
+
+        mockMvc.perform(get("/api/cockpit/v1/monitoring-points/MP-SNAP")
+                        .param("snapshotAt", "2026-09-02T10:00:00+08:00"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.devices[0].deviceCode").value("EQ-001"));
+    }
+
     @Test
     void controllerOnlyExposesAuthenticatedReadOnlyOperations() {
         assertTrue(Arrays.stream(CockpitMonitoringPointDetailController.class.getDeclaredMethods())

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

@@ -24,6 +24,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
 import java.util.stream.Collectors;
 
 /**
@@ -39,6 +41,9 @@ import java.util.stream.Collectors;
  *   <li>类型字典:{@code equipment_type}(行业由 {@code parent_id} 根推导:1 供水、2 排水、3 燃气、4 窨井)。</li>
  * </ul>
  *
+ * <p>显式 {@code snapshotAt} 会在适配器进程内固定首次读取结果;地图与详情端点通过同一适配器实例共享该结果,
+ * 后续相同时间戳请求不会重新读取变化中的点位关联数据。
+ *
  * <p><b>如实接线,不臆造</b>:现网没有「坐标是否已校核」字段,故一律按未校核(
  * {@code coordinateVerified=false})上报,由冻结字典裁决为不可渲染;不为了「图上有东西」而伪造校验状态。
  * 现网 {@code monitor_point} 也没有行业/类型列,点位的 {@code typeCode} 只能在其关联设备类型唯一时推导。
@@ -55,6 +60,7 @@ public class BusinessCockpitMapSnapshotAdapter implements CockpitMapSnapshotAdap
     private final EquipmentTypeService equipmentTypeService;
     private final BusinessCockpitDeviceFactResolver deviceFactResolver;
     private final Clock clock;
+    private final ConcurrentMap<String, CockpitMapSnapshot> snapshots = new ConcurrentHashMap<>();
 
     public BusinessCockpitMapSnapshotAdapter(
             MonitorPointService monitorPointService,
@@ -72,6 +78,10 @@ public class BusinessCockpitMapSnapshotAdapter implements CockpitMapSnapshotAdap
     @Override
     public CockpitMapSnapshot load(String snapshotAt) {
         String resolvedSnapshotAt = snapshotAt == null ? businessTime() : snapshotAt;
+        return snapshots.computeIfAbsent(resolvedSnapshotAt, this::buildSnapshot);
+    }
+
+    private CockpitMapSnapshot buildSnapshot(String resolvedSnapshotAt) {
 
         Map<Integer, EquipmentType> types = equipmentTypes();
         List<MonitorPoint> points = safeList(monitorPointService.list());

+ 29 - 5
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/point/CockpitMonitoringPointDetailService.java

@@ -62,12 +62,15 @@ public class CockpitMonitoringPointDetailService {
             throw new CockpitInvalidRequestException("监测点编码不能为空");
         }
         String normalizedCode = monitoringPointCode.trim();
-        if (!isBlank(snapshotAt)) {
+        if (snapshotAt != null) {
             validateSnapshotAt(snapshotAt);
         }
         CockpitMonitoringPointDetail detail;
-        if (!isBlank(snapshotAt) && mapSnapshotAdapter != null) {
-            detail = loadFromSnapshot(normalizedCode, snapshotAt.trim());
+        if (snapshotAt != null) {
+            if (mapSnapshotAdapter == null) {
+                throw new CockpitSnapshotExpiredException("snapshot source unavailable");
+            }
+            detail = loadFromSnapshot(normalizedCode, snapshotAt);
         } else {
             detail = adapter.load(normalizedCode);
         }
@@ -192,14 +195,35 @@ public class CockpitMonitoringPointDetailService {
         }
         Map<String, CockpitMonitoringPointDeviceSnapshot> byCode = new LinkedHashMap<>();
         for (CockpitMonitoringPointDeviceSnapshot device : devices) {
-            if (device == null || isBlank(device.getDeviceCode())) {
+            if (device == null) {
+                continue;
+            }
+            String code = trimToNull(device.getDeviceCode());
+            if (code == null) {
                 continue;
             }
-            byCode.putIfAbsent(device.getDeviceCode().trim(), device);
+            byCode.putIfAbsent(code, canonicalDevice(device, code));
         }
         return new ArrayList<>(byCode.values());
     }
 
+    private static CockpitMonitoringPointDeviceSnapshot canonicalDevice(
+            CockpitMonitoringPointDeviceSnapshot device, String code) {
+        return new CockpitMonitoringPointDeviceSnapshot(
+                code,
+                device.getDeviceName(),
+                device.getDeviceTypeName(),
+                device.getLongitude(),
+                device.getLatitude(),
+                device.getCoordinateValidation(),
+                device.isOnline(),
+                device.isAlarm(),
+                device.isWarning(),
+                device.isWorkOrderInProgress(),
+                device.getStatusReasons(),
+                device.getStatusTime());
+    }
+
     /**
      * 与 map-snapshot 对齐:snapshotAt 必须是可解析的带偏移 ISO-8601 时间戳,
      * 否则按无效请求(INVALID_REQUEST 400)拒绝,避免畸形时间戳落入 404/200。