Просмотр исходного кода

refactor(cockpit): 统一显示聚合控制器路由与异常出口

Controller 提到类级 /api/cockpit/v1、复用 BaseCockpitController 的 requestId;成员游标过期迁入 CockpitExceptionAdvice,显示服务把底层快照/读取异常归一为既有错误载荷消息;URL/状态码/类别保持不变。
Kazerin 1 неделя назад
Родитель
Сommit
05047127e0

+ 2 - 2
docs/agents/cockpit-controller-standard.md

@@ -21,7 +21,7 @@
 ## 校验与错误
 
 - 请求校验使用已有类型化异常,并交由 `CockpitExceptionAdvice` 转成统一错误响应;不在每个方法里捕获异常后手工拼接错误 JSON。
-- `@ExceptionHandler` 留在统一 Advice。仅当某个既有端点契约必须返回其专属错误载荷且不能由统一 Advice 表达时,才允许局部处理;需说明原因并复用该端点既有错误工厂。`CockpitMapDisplayController` 是此类历史特例,不作为新增接口的默认模板。
+- `@ExceptionHandler` 留在统一 Advice。仅当某个既有端点契约必须返回其专属错误载荷且不能由统一 Advice 表达时,才允许局部处理;需说明原因并复用该端点既有错误工厂。显示聚合端点已迁入统一 Advice(票 10),不再作为局部处理先例。
 - 只有确有专属请求约束时才在 Controller 做轻量校验;字段、授权范围、业务状态和数据完整性由相应 Service/领域层负责。
 
 ## 修改前检查
@@ -33,4 +33,4 @@
 
 ## 现存差异
 
-本目录存在格式不完全一致的历史代码:部分 Controller 使用通配 import 或长参数单行;`CockpitMapDisplayController` 把完整 `/api/cockpit/v1/...` 路径写在方法映射上且有局部异常处理;视频端点覆盖请求 ID 解析并返回 201/202。新增代码以本约定和共享基类/Advice 为准;修改旧端点时只在任务涉及范围内逐步贴齐,不为纯格式统一做无关重写,不改变既有 API 契约。
+本目录存在格式不完全一致的历史代码:部分 Controller 使用通配 import 或长参数单行;视频端点覆盖请求 ID 解析并返回 201/202。新增代码以本约定和共享基类/Advice 为准;修改旧端点时只在任务涉及范围内逐步贴齐,不为纯格式统一做无关重写,不改变既有 API 契约。

+ 8 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitExceptionAdvice.java

@@ -6,6 +6,7 @@ import com.zksy.cockpit.foundation.CockpitErrorCategory;
 import com.zksy.cockpit.foundation.CockpitErrorPayload;
 import com.zksy.cockpit.foundation.CockpitInvalidCodeException;
 import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitMemberCursorExpiredException;
 import com.zksy.cockpit.foundation.CockpitReadException;
 import com.zksy.cockpit.foundation.CockpitSnapshotExpiredException;
 import com.zksy.cockpit.foundation.CockpitMonitoringPointNotFoundException;
@@ -64,6 +65,13 @@ public class CockpitExceptionAdvice {
         return error(HttpStatus.BAD_REQUEST, CockpitErrorCategory.SNAPSHOT_EXPIRED, exception.getMessage(), request);
     }
 
+    @ExceptionHandler(CockpitMemberCursorExpiredException.class)
+    public ResponseEntity<AjaxResult> memberCursorExpired(CockpitMemberCursorExpiredException exception,
+            HttpServletRequest request) {
+        return error(HttpStatus.BAD_REQUEST, CockpitErrorCategory.MEMBER_CURSOR_EXPIRED,
+                exception.getMessage(), request);
+    }
+
     @ExceptionHandler({CockpitDeviceNotFoundException.class, CockpitEntityNotFoundException.class, CockpitMonitoringPointNotFoundException.class})
     public ResponseEntity<AjaxResult> notFound(RuntimeException exception, HttpServletRequest request) {
         return error(HttpStatus.NOT_FOUND, CockpitErrorCategory.NOT_FOUND, exception.getMessage(), request);

+ 5 - 53
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitMapDisplayController.java

@@ -2,35 +2,24 @@ package com.zksy.web.controller.cockpit;
 
 import com.zksy.cockpit.display.CockpitMapDisplayResponse;
 import com.zksy.cockpit.display.CockpitMapDisplayService;
-import com.zksy.cockpit.foundation.CockpitErrorPayload;
-import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
-import com.zksy.cockpit.foundation.CockpitMemberCursorExpiredException;
-import com.zksy.cockpit.foundation.CockpitReadException;
-import com.zksy.cockpit.foundation.CockpitSnapshotExpiredException;
 import com.zksy.common.core.domain.AjaxResult;
-import com.zksy.common.utils.StringUtils;
-import com.zksy.common.utils.uuid.IdUtils;
-import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
-import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestHeader;
+import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
 
-import javax.servlet.http.HttpServletRequest;
-
 @RestController
-public class CockpitMapDisplayController {
-    private static final String REQUEST_ID_HEADER = "X-Request-Id";
-
+@RequestMapping("/api/cockpit/v1")
+public class CockpitMapDisplayController extends BaseCockpitController {
     private final CockpitMapDisplayService displayService;
 
     public CockpitMapDisplayController(CockpitMapDisplayService displayService) {
         this.displayService = displayService;
     }
 
-    @GetMapping("/api/cockpit/v1/map-display-buckets")
+    @GetMapping("/map-display-buckets")
     public ResponseEntity<AjaxResult> buckets(
             @RequestParam(value = "bbox", required = false) String bbox,
             @RequestParam(value = "zoomBand", required = false) Integer zoomBand,
@@ -46,7 +35,7 @@ public class CockpitMapDisplayController {
         return ResponseEntity.ok(AjaxResult.success(response));
     }
 
-    @GetMapping("/api/cockpit/v1/map-display-bucket-members")
+    @GetMapping("/map-display-bucket-members")
     public ResponseEntity<AjaxResult> members(
             @RequestParam(value = "cursor", required = false) String cursor,
             @RequestParam(value = "search", required = false) String search,
@@ -56,41 +45,4 @@ public class CockpitMapDisplayController {
                 cursor, search, pageSize);
         return ResponseEntity.ok(AjaxResult.success(response));
     }
-
-    @ExceptionHandler(CockpitInvalidRequestException.class)
-    public ResponseEntity<AjaxResult> handleInvalidRequest(
-            HttpServletRequest request, CockpitInvalidRequestException exception) {
-        return badRequest(displayService.invalidRequest(resolveRequestId(request.getHeader(REQUEST_ID_HEADER)),
-                exception.getMessage()));
-    }
-
-    @ExceptionHandler(CockpitMemberCursorExpiredException.class)
-    public ResponseEntity<AjaxResult> handleCursorExpired(
-            HttpServletRequest request, CockpitMemberCursorExpiredException exception) {
-        return badRequest(displayService.cursorExpired(resolveRequestId(request.getHeader(REQUEST_ID_HEADER)),
-                exception.getMessage()));
-    }
-
-    @ExceptionHandler(CockpitSnapshotExpiredException.class)
-    public ResponseEntity<AjaxResult> handleSnapshotExpired(HttpServletRequest request) {
-        return badRequest(displayService.snapshotExpired(
-                resolveRequestId(request.getHeader(REQUEST_ID_HEADER))));
-    }
-
-    @ExceptionHandler(CockpitReadException.class)
-    public ResponseEntity<AjaxResult> handleReadFailure(HttpServletRequest request) {
-        CockpitErrorPayload payload = displayService.serverError(
-                resolveRequestId(request.getHeader(REQUEST_ID_HEADER)));
-        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
-                .body(new AjaxResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), payload.getMessage(), payload));
-    }
-
-    private ResponseEntity<AjaxResult> badRequest(CockpitErrorPayload payload) {
-        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
-                .body(new AjaxResult(HttpStatus.BAD_REQUEST.value(), payload.getMessage(), payload));
-    }
-
-    private String resolveRequestId(String requestId) {
-        return StringUtils.isNotEmpty(requestId) ? requestId : IdUtils.fastSimpleUUID();
-    }
 }

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

@@ -0,0 +1,110 @@
+package com.zksy.web.controller.cockpit;
+
+import com.zksy.cockpit.display.CockpitMapDisplayResponse;
+import com.zksy.cockpit.display.CockpitMapDisplayService;
+import com.zksy.cockpit.foundation.CockpitInvalidRequestException;
+import com.zksy.cockpit.foundation.CockpitMemberCursorExpiredException;
+import com.zksy.cockpit.foundation.CockpitReadException;
+import com.zksy.cockpit.foundation.CockpitSnapshotExpiredException;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
+
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.util.Collections;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+class CockpitMapDisplayControllerTest {
+    private static final String SNAPSHOT = "2026-11-25T10:00:00+08:00";
+    private static final Clock CLOCK = Clock.fixed(
+            Instant.parse("2026-11-25T02:00:00Z"), ZoneOffset.ofHours(8));
+
+    private CockpitMapDisplayService service;
+    private MockMvc mockMvc;
+
+    @BeforeEach
+    void setUp() {
+        service = mock(CockpitMapDisplayService.class);
+        mockMvc = MockMvcBuilders.standaloneSetup(new CockpitMapDisplayController(service))
+                .setControllerAdvice(new CockpitExceptionAdvice(CLOCK))
+                .build();
+    }
+
+    @Test
+    void classLevelRouteKeepsBucketsUrlAndPayload() throws Exception {
+        when(service.buckets(anyString(), anyString(), any(), any(), any(), any(), any(), any()))
+                .thenReturn(response());
+        mockMvc.perform(get("/api/cockpit/v1/map-display-buckets")
+                        .header("X-Request-Id", "display-request-001")
+                        .param("bbox", "110.39,28.43,110.4,28.44")
+                        .param("zoomBand", "4"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.requestId").value("display-request-001"))
+                .andExpect(jsonPath("$.data.contract").value("display-buckets-v1"))
+                .andExpect(jsonPath("$.data.statusVersion").value(SNAPSHOT));
+    }
+
+    @Test
+    void invalidRequestUsesUnifiedAdvice() throws Exception {
+        when(service.buckets(anyString(), anyString(), any(), any(), any(), any(), any(), any()))
+                .thenThrow(new CockpitInvalidRequestException("bbox 格式不合法"));
+        mockMvc.perform(get("/api/cockpit/v1/map-display-buckets")
+                        .header("X-Request-Id", "display-request-002")
+                        .param("bbox", "bad")
+                        .param("zoomBand", "4"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"))
+                .andExpect(jsonPath("$.data.message").value("bbox 格式不合法"))
+                .andExpect(jsonPath("$.data.requestId").value("display-request-002"));
+    }
+
+    @Test
+    void cursorExpiredUsesUnifiedAdvice() throws Exception {
+        when(service.members(anyString(), anyString(), any(), any()))
+                .thenThrow(new CockpitMemberCursorExpiredException("成员游标已失效,请重新加载聚合桶"));
+        mockMvc.perform(get("/api/cockpit/v1/map-display-bucket-members")
+                        .header("X-Request-Id", "display-request-003")
+                        .param("cursor", "expired"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("MEMBER_CURSOR_EXPIRED"))
+                .andExpect(jsonPath("$.data.message").value("成员游标已失效,请重新加载聚合桶"));
+    }
+
+    @Test
+    void snapshotExpiredAndReadFailureKeepExistingCategories() throws Exception {
+        when(service.buckets(anyString(), anyString(), any(), any(), any(), any(), any(), any()))
+                .thenThrow(new CockpitSnapshotExpiredException("地图快照已失效,请重新加载"));
+        mockMvc.perform(get("/api/cockpit/v1/map-display-buckets")
+                        .param("bbox", "110.39,28.43,110.4,28.44")
+                        .param("zoomBand", "4"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("SNAPSHOT_EXPIRED"))
+                .andExpect(jsonPath("$.data.message").value("地图快照已失效,请重新加载"));
+
+        when(service.members(anyString(), anyString(), any(), any()))
+                .thenThrow(new CockpitReadException("显示聚合数据暂不可用"));
+        mockMvc.perform(get("/api/cockpit/v1/map-display-bucket-members")
+                        .param("cursor", "c"))
+                .andExpect(status().isInternalServerError())
+                .andExpect(jsonPath("$.data.category").value("SERVER_ERROR"))
+                .andExpect(jsonPath("$.data.message").value("显示聚合数据暂不可用"));
+    }
+
+    private static CockpitMapDisplayResponse response() {
+        return new CockpitMapDisplayResponse("display-request-001", SNAPSHOT, SNAPSHOT, 4,
+                "110.39,28.43,110.4,28.44", 1000, false,
+                new CockpitMapDisplayResponse.Filters(null, null, null, "NONE", null, null),
+                Collections.emptyList());
+    }
+}

+ 13 - 5
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/display/CockpitMapDisplayService.java

@@ -269,9 +269,17 @@ public class CockpitMapDisplayService {
         CockpitMapSnapshotResponse.MapFilter filter = null;
         boolean complete = false;
         for (int page = 1; page <= MAX_SNAPSHOT_PAGES; page += 1) {
-            CockpitMapSnapshotResponse response = mapSnapshotService.load(
-                    requestId, page, SNAPSHOT_PAGE_SIZE, token,
-                    industry, district, deviceType, pointStatus);
+            CockpitMapSnapshotResponse response;
+            try {
+                response = mapSnapshotService.load(
+                        requestId, page, SNAPSHOT_PAGE_SIZE, token,
+                        industry, district, deviceType, pointStatus);
+            } catch (CockpitSnapshotExpiredException exception) {
+                // 保持旧 Controller 的错误载荷口径,不把底层英文/内部原因透给调用方。
+                throw new CockpitSnapshotExpiredException("地图快照已失效,请重新加载");
+            } catch (CockpitReadException exception) {
+                throw new CockpitReadException("显示聚合数据暂不可用");
+            }
             actualSnapshotAt = response.getSnapshotAt();
             filter = response.getMapFilter();
             points.addAll(response.getMonitoringPoints());
@@ -283,11 +291,11 @@ public class CockpitMapDisplayService {
             token = response.getSnapshotAt();
         }
         if (actualSnapshotAt == null) {
-            throw new CockpitSnapshotExpiredException("地图快照时间戳缺失");
+            throw new CockpitSnapshotExpiredException("地图快照已失效,请重新加载");
         }
         if (!complete) {
             // 不静默截断:返回半份桶会让成员数和业务总数同时失真。
-            throw new CockpitReadException("地图快照分页超过安全上限,无法完整聚合");
+            throw new CockpitReadException("显示聚合数据暂不可用");
         }
         return new Rows(actualSnapshotAt, true, points, equipment, filter);
     }