From ba3581fc9d611b16ac3ac64761f333fe449a19ee Mon Sep 17 00:00:00 2001 From: my_local_kimi_dev2 Date: Mon, 30 Nov 2026 16:48:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(mcp):=20=E6=96=B0=E5=A2=9E=E5=87=BA?= =?UTF-8?q?=E7=BA=B8=E6=9C=BA=E9=80=9A=E4=BF=A1=E6=97=A5=E5=BF=97=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E5=B7=A5=E5=85=B7=20hardware.socketlog.list.query?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 对应老系统 SocketLogController /hardwareLog/listByPage,读 ES 月索引 socket_log_yyyyMM - 双集群按 Redis Dictionary.SocketLogPath 切换,返回 cluster 便于排障 - 拍板:不加行级 ACL、允许服务 Token、logType 0-18/99、srcLogContent 不截断、 不做名称富化、rows 默认 20 上限 100、索引不存在返回空 + notice --- .../doc/agent-mcp-tools-reference.md | 23 + .../doc/socket-log-list-mcp-design.md | 405 ++++++++++++++++++ xiaoqu-agent-service/sql/seed-dev.sql | 10 + .../me/iiv/agent/es/SocketLogEsGateway.java | 164 +++++++ .../iiv/agent/es/SocketLogEsGatewayImpl.java | 205 +++++++++ .../me/iiv/agent/mcp/tool/SocketLogTools.java | 340 +++++++++++++++ .../agent/es/SocketLogEsGatewayImplTest.java | 245 +++++++++++ .../agent/mcp/tool/SocketLogToolsTest.java | 330 ++++++++++++++ 8 files changed, 1722 insertions(+) create mode 100644 xiaoqu-agent-service/doc/socket-log-list-mcp-design.md create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGateway.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGatewayImpl.java create mode 100644 xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/SocketLogTools.java create mode 100644 xiaoqu-agent-service/src/test/java/me/iiv/agent/es/SocketLogEsGatewayImplTest.java create mode 100644 xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/SocketLogToolsTest.java diff --git a/xiaoqu-agent-service/doc/agent-mcp-tools-reference.md b/xiaoqu-agent-service/doc/agent-mcp-tools-reference.md index b95420b..7e1df46 100644 --- a/xiaoqu-agent-service/doc/agent-mcp-tools-reference.md +++ b/xiaoqu-agent-service/doc/agent-mcp-tools-reference.md @@ -1386,6 +1386,29 @@ --- +## 59. hardware.socketlog.list.query + +出纸机通信日志分页查询(只读),对应老系统 `SocketLogController` 的 `/hardwareLog/listByPage`。 + +- 分类:hardware | 类型:读(readOnlyHint=true) +- 数据源:ES 月别名 `socket_log_yyyyMM`(物理索引 `socket_log_yyyyMMNN`);集群由 Redis db5 + `Dictionary.SocketLogPath` 决定:`offline`→本地集群,`online`/缺失→云集群;返回体带 `cluster` 便于排障。 +- 入参:`snCode`(必填,1~64 字符,`match_phrase`);`logType`(多选,0-18、99); + `startTime`/`endTime`(`yyyy-MM-dd` 或 `yyyy-MM-dd HH:mm:ss`,必须同月且同时传或同时不传,缺省当天); + `page`(默认 1);`rows`(默认 20、上限 100)。 +- 查询:`createTime` 为 date 类型,range 必须发 **epoch 毫秒**(Asia/Shanghai);排序 `createTime desc, id desc`; + `track_total_hits=true` 取精确总数;`from+size` 超 10000 按窗口截断并在 notice 说明。 +- 返回:`snCode/cluster/index/total/totalPages/page/rows/records/notice`;`records` 为索引全字段加 + `logTypeText/messageTypeText/useTypeText` 中文文案,`srcLogContent` 原样返回不截断。 +- 空/异常:目标月份索引不存在时返回 `total=0` + notice(不报 500);Redis/ES 连接失败返回 `UPSTREAM_UNAVAILABLE`; + 参数非法(snCode 为空、时间格式/跨月、logType 非法)返回 `INVALID_ARGUMENT`。 +- 权限:无行级 ACL(2026-11-30 拍板对齐老接口,仅靠 Token scope 约束能力面);允许用户 Token 与服务 Token; + prod 只绑研发专用 scope 6(code=code),dev 绑测试专用 scope(code=test)与 ops-query。 + +详细设计见 [socket-log-list-mcp-design](socket-log-list-mcp-design.md)。 + +--- + ## 附录:在线查看工具清单 ```bash diff --git a/xiaoqu-agent-service/doc/socket-log-list-mcp-design.md b/xiaoqu-agent-service/doc/socket-log-list-mcp-design.md new file mode 100644 index 0000000..769c41b --- /dev/null +++ b/xiaoqu-agent-service/doc/socket-log-list-mcp-design.md @@ -0,0 +1,405 @@ +# 设备通信日志 MCP 工具设计(hardware.socketlog.list.query) + +对应老接口:`POST /hardwareLog/listByPage`(xiaoqu-franchisee `controller/hard/SocketLogController.java:107-194`)。 + +> 上一版误按 `HardwareLogController.queryByPage`(设备操作日志)设计,本版已按 `SocketLogController` +> 重做;误建的 `hardware-log-list-mcp-design.md` 已删除。本文件是唯一设计稿。 + +## 1. 结论摘要 + +- 工具名:`hardware.socketlog.list.query`,category=`hardware`,kind=`read`。 +- 数据源:出纸机通信日志月索引 `socket_log_yyyyMM`,**双 ES 集群**,由 Redis 字典 + `Dictionary.SocketLogPath` 决定读云集群还是本地集群(老接口原语义)。 +- 查询条件:`snCode` 必填;`logType` 多选;时间范围必须是同一个月,缺省查当天。 +- 安全:按王恒 2026-11-30 拍板**不施加行级 ACL**(对齐老接口,只靠 Token scope 约束能力面); + 分页默认 20、上限 100,深分页按 ES `max_result_window=10000` 保护。 +- 只读:不实现 `/sourceExport`、`/customerExport` 两个导出接口,不做任何写操作。 + +## 2. 老接口行为(行号级) + +### 2.1 入参 + +`SocketLogPageInput extends PageInput`(`controller/input/SocketLogPageInput.java`): + +| 字段 | 说明 | +|---|---| +| `snCode` | 设备 SN,必填;为空直接返回失败「请传递设备号」(`SocketLogController.java:112-114`) | +| `quertTime` | 查询日期范围,格式 `yyyy-MM-dd ~ yyyy-MM-dd`,Swagger 注明必须同一个月(`:14-15`) | +| `logType` | 日志类型多选,逗号分隔(`:16`,注释列 0-14) | +| `page` / `rows` | 页码 / 每页条数;`PageInput` 默认 10 条、上限 999(`PageInput.java:26-29`) | + +### 2.2 查询构造 + +`listByPage`(`:107-194`)全部走 `BaseSearchSupportImpl.findListByPage`: + +| 条件 | 构造 | 实际 ES 查询 | +|---|---|---| +| `snCode` | `Search.type=0` + String(`:121-125`) | `match snCode`(standard analyzer,大小写不敏感、可能分词) | +| 时间范围 | `Search.type=1`(`:135-140` / `:147-152`) | `range createTime` 闭区间,值为 `yyyy-MM-dd HH:mm:ss` 解析出的 `Date` | +| `logType` | `Search.type=2`(`:154-162`) | `terms logType`(数值) | +| 排序 | `sortMap.put("createTime", DESC)`(`:119`) | `sort createTime desc`,无第二排序键 | +| 分页 | `SearchPagination(rows, null, page)`(`:118`) | `from=(page-1)*rows`、`size=rows`,`track_total_hits=true` | + +### 2.3 索引与集群切换(本接口最容易搞错的地方) + +**索引名**(`:126-153`): + +- 传了 `quertTime`:取**开始日期所在月**,`socket_log_` + `yyyyMM`; +- 没传:取**服务器当天所在月**,`socket_log_` + `yyyyMM`; +- 跨月范围不会报错,但只查开始月索引,结束月数据被静默丢弃(老接口的坑)。 + +生产/开发实测:`socket_log_yyyyMM` 是**别名**,物理索引是 `socket_log_yyyyMMNN`(NN 为月内序号)。 +月别名会指向该月全部序号索引;云集群上的清理任务只保留最新一个物理索引 +(`SocketLogIndexCleanTask.java`),本地集群保留历史。 + +**集群切换**(`:177-192`): + +```java +Object SocketLogPath = redisTemplate.opsForHash().get(Constants.Dictionary, "SocketLogPath"); +if (SocketLogPath != null && "offline".equals(SocketLogPath + "")) { + socketLogESService2.findListByPage(...); // es_hosts2 / restClient2,本地集群 +} else { + socketLogESService.findListByPage(...); // es_hosts / restClient,云集群 +} +``` + +- 字典 key:Redis db5 hash `Dictionary` 的 `SocketLogPath` 字段; +- 只有值为 `offline` 才走本地集群,其余(含 key 不存在)都走云集群; +- 2026-11-30 实测:**dev=`online`(云)**,**prod=`offline`(本地)**。 + +### 2.4 出参 + +`PageOutput`(`controller/output/PageOutput.java`): + +- `page`:当前页; +- `records`:**总条数**(`result.getPagination().getTotalCount()`); +- `total`:**总页数**(`getTotalPage()`,`Pagination.java:37-42`); +- `rows`:`SocketLogEntity` 列表,全字段: + `id/createId/createTime/modifyId/modifyTime/softDelete/snCode/buildingId/districtId/propertyId/agentId/logType/logContent/useType/messageType/srcLogContent/tableName`。 + +注意:老接口 `records`/`total` 的命名与直觉相反,MCP 侧会改成 `total`=总条数、`totalPages`=总页数。 + +### 2.5 老接口的坑 + +1. **完全无行级权限**:任何登录用户可查任意 SN 的原始通信日志。 +2. **跨月静默丢数据**:只按开始月选索引,结束月部分不查也不报错。 +3. **`snCode` 用 `match`**:standard analyzer 会把 `AB-123` 拆成 `ab`/`123`,可能误配; + 本次改用 `match_phrase`(见 §4)。 +4. **深层分页无保护**:`from+size` 超过 ES `max_result_window`(默认 10000)会被 ES 拒绝, + 老接口直接把 500 抛给前端。 +5. **索引不存在直接 404**:`socketLog_yyyyMM` 别名不存在时 ES 返回 `index_not_found_exception`, + 老接口未捕获。 +6. **不校验 `quertTime` 格式**:`DateToConverter.parseDate` 失败返回 null,range 查询行为不可控。 +7. **无 `softDelete` 过滤**:当前数据全是 0,但老接口不看该字段。 +8. **`tableName` 字段误导**:文档里的 `tableName` 是写入端打的日期标签(如 `socket_log_20261130`), + 不是实际查询索引,不要拿它拼索引。 + +## 3. 实测 mapping 与数据(2026-11-30,只读) + +### 3.1 集群与字典 + +| 环境 | Redis `Dictionary.SocketLogPath` | 老接口实际集群 | 地址 | +|---|---|---|---| +| dev | `online` | 云集群 | `192.168.1.152:9200` | +| prod | `offline` | **本地集群** | `114.253.9.110:19800` | + +> 本服务 `EsClientConfig` 已按 `app.es.cloud.*` / `app.es.local.*` 提供两个低阶 +> `RestClient` bean,生产环境变量已配好,可直接复用。 + +### 3.2 索引与数据量 + +| 环境/集群 | 当前月别名 | 物理索引 | 文档数 | 大小 | +|---|---|---|---|---| +| dev 云 | `socket_log_202611` | `socket_log_20261104` | 276 | 278.7 kb | +| prod 云 | `socket_log_202611` | `socket_log_20261104` | 273,680,095 | 156.5 gb | +| prod 本地 | `socket_log_202611` | `socket_log_20261101`~`20261104` | **1,426,950,061** | 约 380 gb(4 个索引合计) | + +- prod 本地按 `snCode + 约一日范围`(11-25 08:00~23:59)实测命中 1058 条,**耗时约 4.8s** + (4 分片 × 4 索引);本服务 ES 客户端 socketTimeout=60s,可覆盖。 +- 云集群只保留最新物理索引;切回 `online` 后历史月份不可查。本地集群保留历史月别名。 + +### 3.3 Mapping(dev 云 / prod 本地一致) + +| 字段 | 类型 | 备注 | +|---|---|---| +| `id` | long | | +| `createTime` / `modifyTime` | date | `_source` 为 ISO 文本,`range` 查询必须发 **epoch 毫秒** | +| `snCode` / `logContent` / `srcLogContent` / `tableName` | text + `.keyword` | keyword `ignore_above=256` | +| `logType` / `messageType` / `useType` / `softDelete` | long | | +| `agentId` / `propertyId` / `districtId` / `buildingId` / `createId` / `modifyId` | long | 可用于行级 ACL 过滤 | + +dev 实测: + +- `softDelete` 全部 0;`agentId`/`propertyId`/`districtId` 缺失 0 条(ACL 可用)。 +- `logType` 分布:1 出纸 120、0 下上线 68、2 rfid 34、3 报警 28、16 自由指令 16、 + 10 设备心跳 4、6 背景值检测 2、7 锁 2、99 未知指令 2。 +- `logContent` 最大 83 字符、`srcLogContent` 最大 145 字符(本页样本,未发现超长内容)。 + +### 3.4 时间格式 + +`createTime` 为 `date` 类型,直接发 `"2026-11-01 00:00:00"` 会被 400 拒绝; +必须转 **epoch 毫秒(Asia/Shanghai)**,或 ISO 带时区。老系统能跑是因为 transport 客户端 +把 `Date` 序列化成 epoch 毫秒。MCP 侧统一用 epoch 毫秒。 + +### 3.5 索引不存在 + +`socket_log_202610`(不存在的别名)实测返回 HTTP 404 + +`index_not_found_exception`;低阶客户端会抛 `ResponseException`,gateway 需单独识别。 + +## 4. 设计决策(2026-11-30 王恒已拍板) + +| # | 决策 | 结论 | +|---|---|---| +| 1 | 集群选择 | 完整复刻老接口:读 Redis `Dictionary.SocketLogPath`,`offline`→本地,其余→云;返回体带 `cluster` 便于排障 | +| 2 | 索引选择 | `socket_log_` + 开始时间 `yyyyMM`;**时间范围必须同一个月**,跨月直接 `INVALID_ARGUMENT`,不静默丢数据 | +| 3 | 行级权限 | **不施加**(拍板:不加)。与老接口一致,仅依赖 Token scope 约束工具能力面;返回体不按 `agentId`/`propertyId` 过滤 | +| 4 | snCode 匹配 | `match_phrase snCode`,修掉老 `match` 的分词误配;大小写不敏感 | +| 5 | logType | `List` 多选,`terms` 查询;校验 0-18、99,映射中文文案 | +| 6 | 时间入参 | `startTime`/`endTime`,支持 `yyyy-MM-dd` 与 `yyyy-MM-dd HH:mm:ss`;日期型 end 补 23:59:59;两者都传或都不传,缺省查当天 | +| 7 | 分页 | 默认 20、上限 100;`from+size` 超 10000 按窗口截断并 notice;`total` 精确条数 + `totalPages` | +| 8 | 排序 | `createTime desc, id desc`(老接口只有 `createTime desc`,加 id 保证稳定) | +| 9 | 返回字段 | 返回 `SocketLogEntity` 全字段 + `logTypeText/messageTypeText/useTypeText`;`srcLogContent` 不截断 | +| 10 | 索引不存在 | 不报 500:返回空结果 + `notice`(该月索引在当前集群不存在),`total=0` | +| 11 | softDelete | 与老接口一致不过滤(当前数据全 0);在文档注明 | +| 12 | 名称富化 | v1 不做:不查 user/agent/property/district 名称,只返回 id,避免给 ES 查询引入额外 DB 依赖 | +| 13 | 导出 | 不做 `/sourceExport`、`/customerExport`,本期只做列表 | +| 14 | Token | **允许**用户 Token 与服务 Token(拍板:允许);因不施加行级 ACL,两者查询口径一致 | + +拍板结论(2026-11-30):1=不加 ACL;2=允许服务 Token;3=logType 白名单 0-18、99; +4=`srcLogContent` 不截断;5=不做名称富化;6=分页默认 20、上限 100;7=索引不存在返回空 + notice。 + +## 5. 工具契约 + +### 5.1 元数据 + +``` +name: hardware.socketlog.list.query +category: hardware +kind: read +description: 出纸机通信日志分页查询,对应老系统 /hardwareLog/listByPage(SocketLogController)。 + snCode 必填;logType 多选;时间范围必须同一个月,缺省当天。 + 返回原始通信内容 srcLogContent 与解析内容 logContent。 + 不施加行级 ACL(拍板对齐老接口),仅由 Token scope 控制工具能力面。 + page 默认 1,rows 默认 20、上限 100。 +``` + +### 5.2 入参 + +| 参数 | 类型 | 必填 | 说明 | +|---|---|---|---| +| `snCode` | String | 是 | 设备 SN,去空格后 1~64 字符;`match_phrase snCode` | +| `logType` | List\ | 否 | 日志类型多选;允许 0-18、99;不传=全部 | +| `startTime` | String | 否 | 开始时间,`yyyy-MM-dd` 或 `yyyy-MM-dd HH:mm:ss`,含 | +| `endTime` | String | 否 | 结束时间,同上;日期型补 23:59:59,含;必须与 startTime 同月 | +| `page` | Integer | 否 | 页码,从 1 开始,默认 1 | +| `rows` | Integer | 否 | 每页条数,默认 20,上限 100,超出截断并 notice | + +校验规则: + +- `snCode` 空白 → `INVALID_ARGUMENT`。 +- `startTime`/`endTime` 必须同时传或同时不传;只传一个 → `INVALID_ARGUMENT`。 +- 两者都为空 → 当天 `00:00:00` ~ `23:59:59`。 +- 格式非法、`start > end`、跨自然月 → `INVALID_ARGUMENT`。 +- `logType` 含非法值 → `INVALID_ARGUMENT`。 +- `page < 1` 按 1;`rows < 1` 按默认值。 + +`logType` 文案(取自 `TypeToNameUtils.getLogTypeName`;老 Swagger 只列到 14,实际还有 15-18、99): + +| 值 | 文案 | 值 | 文案 | +|---|---|---|---| +| 0 | 下上线 | 10 | 设备心跳 | +| 1 | 出纸 | 11 | 出纸开关 | +| 2 | rfid | 12 | 出纸口清理 | +| 3 | 报警 | 13 | 出纸模式设定 | +| 4 | 错误 | 14 | 设置亮灯响铃模式 | +| 5 | 有人无人 | 15 | 工程模式设定 | +| 6 | 背景值检测 | 16 | 自由指令 | +| 7 | 锁 | 17 | 三挡纸量检测 | +| 8 | 上纸动作 | 18 | 更改设备类型 | +| 9 | 设备升级 | 99 | 未知指令 | + +`messageType`:0=上行、1=下行;`useType`:0=运维、1=普通人员。 + +### 5.3 出参 + +```json +{ + "snCode": "X1A1200800000055", + "cluster": "cloud", + "index": "socket_log_202611", + "total": 48, + "totalPages": 3, + "page": 1, + "rows": 20, + "records": [ + { + "id": 7528007542032649457, + "createTime": "2026-11-25 15:01:55", + "modifyTime": "2026-11-25 15:01:55", + "snCode": "X1A1200800000055", + "logType": 2, + "logTypeText": "rfid", + "logContent": "rfid识别,rfid=fjklewj1501;长度=18000厘米", + "srcLogContent": "X1A1200800000055:up===RFID:fjklewj1501;===SRC:RFID,0,18000,1.2;===2026-11-25 15:01:55", + "messageType": 0, + "messageTypeText": "上行", + "useType": 1, + "useTypeText": "普通人员", + "agentId": 17, + "propertyId": 177, + "districtId": 318, + "buildingId": 392, + "createId": 0, + "modifyId": 8991, + "softDelete": 0, + "tableName": "socket_log_20261125" + } + ], + "notice": "rows 超过上限 100,已截断为 100" +} +``` + +- `total`:命中总条数(对应老接口 `records`); +- `totalPages`:总页数(对应老接口 `total`); +- `notice`:仅在 rows 截断、深分页截断、索引不存在时出现; +- `cluster`:`cloud` 或 `local`。 + +### 5.4 错误码 + +| 场景 | 错误码 | +|---|---| +| snCode 为空、时间格式非法、跨月、logType 非法、只传一个时间 | `INVALID_ARGUMENT` | +| Redis / ES 连接失败、ES 5xx | `UPSTREAM_UNAVAILABLE` | +| 索引不存在(404) | 不报错,返回空 + notice | + +### 5.5 ES 查询 DSL(示意) + +```json +{ + "from": 0, + "size": 20, + "track_total_hits": true, + "query": { + "bool": { + "filter": [ + { "match_phrase": { "snCode": "X1A1200800000055" } }, + { "range": { "createTime": { "gte": 1795536000000, "lte": 1795622399000 } } }, + { "terms": { "logType": [0, 1, 2] } } + ] + } + }, + "sort": [ + { "createTime": "desc" }, + { "id": "desc" } + ] +} +``` + +- `range` 值必须是 epoch 毫秒; +- 无 ACL:`bool` 里只有 `filter`,不生成 `should`。 + +## 6. 行级 ACL + +**不施加**(2026-11-30 王恒拍板)。与老接口一致:只要 Token 的作用域包含该工具, +即可查询任意 SN 的通信日志。数据可见性完全由 `agent_scope` / `scope_tool` 授权面控制。 +设计稿早期建议的 `agentId`/`propertyId` 行级过滤不实现,`PermissionService` 无需改动。 + +## 7. 与老系统差异 + +| 项 | 老接口 | 新工具 | +|---|---|---| +| 权限 | 无 ACL | 无 ACL(拍板对齐老接口) | +| 跨月 | 静默只查开始月 | 显式拒绝 | +| snCode 匹配 | `match`(可能分词误配) | `match_phrase` | +| 时间格式 | `Date` 隐式序列化 | 显式 epoch 毫秒 | +| 深分页 | 超 10000 直接 500 | 窗口截断 + notice | +| 索引不存在 | 404 异常 | 空结果 + notice | +| 分页默认 | 10 条、上限 999 | 20 条、上限 100 | +| 排序 | `createTime desc` | `createTime desc, id desc` | +| 导出 | 两个导出接口 | 不实现 | + +## 8. 改动清单 + +| 文件 | 改动 | +|---|---| +| `src/main/java/me/iiv/agent/es/SocketLogEsGateway.java` | 新增接口:`search(cluster, index, snCode, logTypes, gteMillis, lteMillis, from, size)` | +| `src/main/java/me/iiv/agent/es/SocketLogEsGatewayImpl.java` | 新增实现:注入 `esCloudRestClient` + `esLocalRestClient`,构造 DSL,解析 `_source`,404 识别 | +| `src/main/java/me/iiv/agent/mcp/tool/SocketLogTools.java` | 新增工具:参数校验、Redis 集群选择、索引名、结果映射 | +| `src/test/java/me/iiv/agent/mcp/tool/SocketLogToolsTest.java` | 新增单测 | +| `src/test/java/me/iiv/agent/es/SocketLogEsGatewayImplTest.java` | 新增 gateway 单测 | +| `doc/agent-mcp-tools-reference.md` | 上线后追加工具章节(§59) | +| `AGENTS.md` | 上线后更新「近期需求示例」 | + +无 DDL、无新表、无配置项变更(复用现有 ES/Redis 配置)。 + +## 9. 测试计划 + +### 9.1 单元测试 + +- 参数:snCode 空、时间格式非法、只传一个时间、start>end、跨月、logType 非法、rows 截断。 +- 集群:Redis 返回 `offline` → local;`online` / null → cloud;Redis 异常 → `UPSTREAM_UNAVAILABLE`。 +- 索引:开始月拼 `socket_log_yyyyMM`;缺省当天;跨月拒绝。 +- 分页:默认 20/1;rows>100 截断;from+size>10000 窗口截断 + notice。 +- 映射:logType 0-18/99 文案;messageType 0/1;useType 0/1;createTime ISO → 文本。 +- 异常:ES 404 → 空 + notice;ES 500 → `UPSTREAM_UNAVAILABLE`。 +- 响应:`total`/`totalPages`/`page`/`rows`/`records` 字段与老接口语义对照。 + +### 9.2 Gateway 测试 + +- DSL:`match_phrase`、`terms logType`、`range` epoch 毫秒、`sort createTime+id`、`from/size`、`track_total_hits`。 +- 404 `index_not_found_exception` 识别。 +- `_source` 解析:日期两种形态、缺失字段、数值字段。 + +### 9.3 测试环境冒烟 + +1. `./deploy/test-up.sh` 起本机测试环境(dev profile,Redis `SocketLogPath=online` → 云集群)。 +2. 用 `scopeCode=test` 签用户 Token,MCP initialize + tools/call。 +3. 用 dev 真实 SN `X1A1200800000055` 查本月:预期 `total>0`,`cluster=cloud`,`index=socket_log_202611`。 +4. 传 `logType=[2]`、时间范围、分页边界各跑一次。 +5. Redis 字典异常场景由单测覆盖(无 ACL 场景)。 +6. 非法参数验证 `INVALID_ARGUMENT`。 +7. 全程只读,不产生任何写操作。 + +### 9.4 生产只读核验 + +- 部署后 `tools/list` 可见;用 prod 真实 SN(如 `X3A41Y0000053453`)查当天: + 预期 `cluster=local`、`index=socket_log_202611`、`total>0`。 +- 观察耗时(本地集群单 SN 单日约 5s),确认不超 60s。 +- 不做任何写操作。 + +## 10. 上线步骤 + +按 `AGENTS.md` 标准流程: + +1. 设计评审(本文档)→ 拍板。 +2. 实现 + 单测 + `./mvnw clean package` 全量通过。 +3. 测试环境冒烟(§9.3)。 +4. `git push origin main` → `./deploy/deploy.sh remote-deploy`。 +5. 幂等绑 prod 研发专用 scope 6(新口径);dev 绑测试专用 scope。 +6. 生产只读核验(§9.4)。 +7. 建 ai-proj 需求(项目 224)+ 任务关联,回写实施记录。 +8. 更新 `doc/agent-mcp-tools-reference.md` 与 `AGENTS.md`。 + +## 11. 拍板结论(2026-11-30) + +| # | 决策点 | 结论 | +|---|---|---| +| 1 | 行级 ACL | **不加**(对齐老接口,仅靠 Token scope) | +| 2 | 服务 Token | **允许** | +| 3 | `logType` 白名单 | **0-18、99**;未来固件新增类型需更新白名单 | +| 4 | `srcLogContent` 截断 | **不截断** | +| 5 | 名称富化 | **不做**,只返回 id | +| 6 | 分页默认值 | **20/100** | +| 7 | 索引不存在 | **返回空 + notice** | + +## 12. 风险与注意事项 + +- **双集群一致性**:prod 读本地集群,dev 读云集群;`SocketLogPath` 被改动会直接切换数据源。 + 返回体带 `cluster`,排障时先看这个字段。 +- **本地集群数据量巨大**:当前月 14.3 亿条 / 380 GB,单 SN 单日查询约 5s;禁止放开 snCode 必填, + 禁止跨月大范围扫描。 +- **云集群只有最新物理索引**:若字典切回 `online`,历史月份会返回空 + notice,不是数据丢失。 +- **无行级 ACL**:能拿到该工具 scope 的调用方可查询任意 SN 的原始通信日志, + 开通 scope 时需按此风险控制(与老接口一致,是明确拍板结果)。 +- **`tableName` 不是索引名**:它只是写入端的日期标签,禁止用于拼查询索引。 +- **`track_total_hits=true`**:精确总数在超大结果集上可能较慢;SN 过滤后可控,保持与老接口一致。 diff --git a/xiaoqu-agent-service/sql/seed-dev.sql b/xiaoqu-agent-service/sql/seed-dev.sql index f61a6c2..0853b5d 100644 --- a/xiaoqu-agent-service/sql/seed-dev.sql +++ b/xiaoqu-agent-service/sql/seed-dev.sql @@ -107,6 +107,16 @@ SELECT s.id, t.id, 0 FROM agent_scope s JOIN tool t WHERE s.code = 'test' AND t.kind = 'write' AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = s.id AND st.tool_id = t.id); +-- 出纸机通信日志(hardware.socketlog.list.query):读工具、无行级 ACL(2026-11-30 拍板)。 +-- dev 绑「测试专用」(code='test') 供用户 Token 冒烟,同时绑 ops-query 供服务 Token 验证(拍板允许服务身份); +-- prod 按新口径只绑研发专用 scope 6。 +INSERT INTO scope_tool (scope_id, tool_id, create_id) +SELECT s.id, t.id, 0 FROM agent_scope s JOIN tool t +WHERE s.soft_delete = 0 AND s.status = 1 + AND (s.code = 'test' OR s.code = 'ops-query') + AND t.name = 'hardware.socketlog.list.query' + AND NOT EXISTS (SELECT 1 FROM scope_tool st WHERE st.scope_id = s.id AND st.tool_id = t.id); + -- 短信验证码提取(sms.vercode.latest.query,REQ-20261113-0009):验证码 = 登录敏感原语, -- 全平台唯一"显式排除业务 scope"的工具——dev 只绑「测试专用」(code='test'),对应 prod 只绑研发专用 scope 6; -- 不进入 operation/hardware/ops-query/sync 等任何其他作用域。 diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGateway.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGateway.java new file mode 100644 index 0000000..38b084c --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGateway.java @@ -0,0 +1,164 @@ +package me.iiv.agent.es; + +import java.util.List; + +/** + * socket_log_yyyyMM(出纸机通信日志)ES 查询网关。 + * 索引在云/本地两个集群都可能有,由调用方按 Redis Dictionary.SocketLogPath 决定集群后传入, + * 本接口只做单次查询,便于单测 mock。 + */ +public interface SocketLogEsGateway { + + /** + * 分页查询单台设备的通信日志。 + * + * @param localCluster true=本地集群,false=云集群 + * @param index 月索引名,如 socket_log_202611(由调用方按 startTime 月份构造) + * @param snCode 设备 SN,match_phrase 精确短语匹配 + * @param logTypes 日志类型多选,null/空=不过滤 + * @param fromMillis createTime 下界(含),epoch 毫秒 + * @param toMillis createTime 上界(含),epoch 毫秒 + * @param from from+size 分页起始偏移 + * @param size 每页条数 + * @return 命中总数、当页记录(按 createTime DESC, id DESC)与索引缺失标记 + */ + Result search(boolean localCluster, String index, String snCode, List logTypes, + long fromMillis, long toMillis, int from, int size); + + /** 单次查询结果;indexMissing=true 表示该月别名在当前集群不存在(total=0、records 为空)。 */ + class Result { + private final long total; + private final List records; + private final boolean indexMissing; + + public Result(long total, List records, boolean indexMissing) { + this.total = total; + this.records = records; + this.indexMissing = indexMissing; + } + + public long getTotal() { + return total; + } + + public List getRecords() { + return records; + } + + public boolean isIndexMissing() { + return indexMissing; + } + } + + /** 单条通信日志(createTime/modifyTime 已统一为 yyyy-MM-dd HH:mm:ss 文本)。 */ + class Record { + private final Long id; + private final Long createId; + private final String createTime; + private final Long modifyId; + private final String modifyTime; + private final Integer softDelete; + private final String snCode; + private final Long buildingId; + private final Long districtId; + private final Long propertyId; + private final Long agentId; + private final Integer logType; + private final String logContent; + private final Integer useType; + private final Integer messageType; + private final String srcLogContent; + private final String tableName; + + public Record(Long id, Long createId, String createTime, Long modifyId, String modifyTime, + Integer softDelete, String snCode, Long buildingId, Long districtId, + Long propertyId, Long agentId, Integer logType, String logContent, + Integer useType, Integer messageType, String srcLogContent, String tableName) { + this.id = id; + this.createId = createId; + this.createTime = createTime; + this.modifyId = modifyId; + this.modifyTime = modifyTime; + this.softDelete = softDelete; + this.snCode = snCode; + this.buildingId = buildingId; + this.districtId = districtId; + this.propertyId = propertyId; + this.agentId = agentId; + this.logType = logType; + this.logContent = logContent; + this.useType = useType; + this.messageType = messageType; + this.srcLogContent = srcLogContent; + this.tableName = tableName; + } + + public Long getId() { + return id; + } + + public Long getCreateId() { + return createId; + } + + public String getCreateTime() { + return createTime; + } + + public Long getModifyId() { + return modifyId; + } + + public String getModifyTime() { + return modifyTime; + } + + public Integer getSoftDelete() { + return softDelete; + } + + public String getSnCode() { + return snCode; + } + + public Long getBuildingId() { + return buildingId; + } + + public Long getDistrictId() { + return districtId; + } + + public Long getPropertyId() { + return propertyId; + } + + public Long getAgentId() { + return agentId; + } + + public Integer getLogType() { + return logType; + } + + public String getLogContent() { + return logContent; + } + + public Integer getUseType() { + return useType; + } + + public Integer getMessageType() { + return messageType; + } + + public String getSrcLogContent() { + return srcLogContent; + } + + public String getTableName() { + return tableName; + } + } +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGatewayImpl.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGatewayImpl.java new file mode 100644 index 0000000..99e014e --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/es/SocketLogEsGatewayImpl.java @@ -0,0 +1,205 @@ +package me.iiv.agent.es; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.Request; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; +import org.elasticsearch.client.RestClient; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.List; + +/** + * socket_log_yyyyMM ES 查询实现。 + * 降级原因同其它 ES 网关:生产两个集群均为 ES 7.7.1,高阶 ElasticsearchClient(7.17)的 + * vendor Content-Type 与 X-Elastic-Product 校验都会失败,业务查询一律用低阶 RestClient。 + * 查询口径对齐老 SocketLogController.listByPage,但修掉其坑: + * snCode 用 match_phrase(老代码 match 经 standard analyzer 可能分词误配)、 + * createTime range 显式发 epoch 毫秒(date 字段不接受空格分隔字符串)、 + * createTime DESC + id DESC 保证稳定排序;索引不存在返回空结果而不是 404 异常。 + */ +@Component +public class SocketLogEsGatewayImpl implements SocketLogEsGateway { + + private static final ZoneId BUSINESS_ZONE = ZoneId.of("Asia/Shanghai"); + private static final DateTimeFormatter TIME_FORMATTER = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(BUSINESS_ZONE); + + private final RestClient cloudRestClient; + private final RestClient localRestClient; + private final ObjectMapper mapper = new ObjectMapper(); + + public SocketLogEsGatewayImpl(@Qualifier("esCloudRestClient") RestClient cloudRestClient, + @Qualifier("esLocalRestClient") RestClient localRestClient) { + this.cloudRestClient = cloudRestClient; + this.localRestClient = localRestClient; + } + + @Override + public Result search(boolean localCluster, String index, String snCode, List logTypes, + long fromMillis, long toMillis, int from, int size) { + ArrayNode filters = mapper.createArrayNode(); + // 老代码 snCode 走 matchQuery(BaseSearchSupportImpl type=0),standard analyzer 可能分词误配; + // 这里改 match_phrase 精确短语匹配 + filters.addObject().putObject("match_phrase").putObject("snCode").put("query", snCode); + // createTime 是 date 类型,range 必须发 epoch 毫秒(yyyy-MM-dd HH:mm:ss 字符串会被 400 拒绝) + ObjectNode range = filters.addObject().putObject("range").putObject("createTime"); + range.put("gte", fromMillis).put("lte", toMillis); + if (logTypes != null && !logTypes.isEmpty()) { + ArrayNode terms = filters.addObject().putObject("terms").putArray("logType"); + logTypes.forEach(terms::add); + } + + ObjectNode body = mapper.createObjectNode(); + body.put("from", from).put("size", size); + body.put("track_total_hits", true); + ObjectNode bool = body.putObject("query").putObject("bool"); + bool.set("filter", filters); + // 老接口只有 createTime DESC;追加 id DESC 保证同一时间的记录分页稳定 + ArrayNode sort = body.putArray("sort"); + sort.addObject().putObject("createTime").put("order", "desc"); + sort.addObject().putObject("id").put("order", "desc"); + + try { + Request req = new Request("POST", "/" + index + "/_search"); + req.setJsonEntity(mapper.writeValueAsString(body)); + Response resp = client(localCluster).performRequest(req); + JsonNode root = mapper.readTree(resp.getEntity().getContent()); + List records = new ArrayList<>(); + for (JsonNode hit : root.at("/hits/hits")) { + JsonNode source = hit.get("_source"); + if (source == null) { + continue; + } + records.add(toRecord(source)); + } + return new Result(root.at("/hits/total/value").asLong(), records, false); + } catch (ResponseException e) { + if (isIndexNotFound(e)) { + // 月别名在当前集群不存在(如云集群只保留最新物理索引):返回空 + 标记,由工具层出 notice + return new Result(0, List.of(), true); + } + throw new IllegalStateException("ES 查询通信日志失败: " + e.getMessage(), e); + } catch (IOException | RuntimeException e) { + throw new IllegalStateException("ES 查询通信日志失败: " + e.getMessage(), e); + } + } + + private RestClient client(boolean localCluster) { + return localCluster ? localRestClient : cloudRestClient; + } + + private static boolean isIndexNotFound(ResponseException e) { + if (e.getResponse().getStatusLine().getStatusCode() != 404) { + return false; + } + try { + if (e.getResponse().getEntity() == null) { + return true; + } + String body = EntityUtils.toString(e.getResponse().getEntity(), StandardCharsets.UTF_8); + return body.contains("index_not_found_exception"); + } catch (IOException ignored) { + // 404 且无法读取响应体时仍按索引不存在处理,避免把可预期的空月变成 500 + return true; + } + } + + private static Record toRecord(JsonNode source) { + return new Record( + longValue(source.get("id")), + longValue(source.get("createId")), + timeText(source.get("createTime")), + longValue(source.get("modifyId")), + timeText(source.get("modifyTime")), + integerValue(source.get("softDelete")), + textValue(source.get("snCode")), + longValue(source.get("buildingId")), + longValue(source.get("districtId")), + longValue(source.get("propertyId")), + longValue(source.get("agentId")), + integerValue(source.get("logType")), + textValue(source.get("logContent")), + integerValue(source.get("useType")), + integerValue(source.get("messageType")), + textValue(source.get("srcLogContent")), + textValue(source.get("tableName"))); + } + + /** + * createTime/modifyTime 在 _source 里是 ISO 文本(2026-11-25T10:30:42+08:00)或 epoch 毫秒数, + * 两种形态都归一为 Asia/Shanghai yyyy-MM-dd HH:mm:ss 文本输出(对齐老系统 Date 格式化口径)。 + */ + private static String timeText(JsonNode value) { + if (value == null || value.isNull()) { + return null; + } + if (value.isNumber()) { + return TIME_FORMATTER.format(Instant.ofEpochMilli(value.longValue())); + } + if (value.isTextual()) { + String text = value.asText(); + if (text.indexOf('T') >= 0) { + try { + return TIME_FORMATTER.format(OffsetDateTime.parse(text)); + } catch (DateTimeParseException e) { + return text; + } + } + return text; + } + return null; + } + + private static String textValue(JsonNode value) { + return value == null || value.isNull() ? null : value.asText(); + } + + /** id 等 long 字段可能是数字或文本;注意 socket_log 的 id 允许负数,不能用无符号解析。 */ + private static Long longValue(JsonNode value) { + if (value == null || value.isNull()) { + return null; + } + if (value.isNumber()) { + return value.longValue(); + } + if (value.isTextual()) { + try { + return Long.valueOf(value.asText().trim()); + } catch (NumberFormatException e) { + return null; + } + } + return null; + } + + private static Integer integerValue(JsonNode value) { + if (value == null || value.isNull()) { + return null; + } + if (value.isNumber()) { + return value.intValue(); + } + if (value.isTextual()) { + try { + return Integer.valueOf(value.asText().trim()); + } catch (NumberFormatException e) { + return null; + } + } + return null; + } +} diff --git a/xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/SocketLogTools.java b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/SocketLogTools.java new file mode 100644 index 0000000..4ac14bb --- /dev/null +++ b/xiaoqu-agent-service/src/main/java/me/iiv/agent/mcp/tool/SocketLogTools.java @@ -0,0 +1,340 @@ +package me.iiv.agent.mcp.tool; + +import me.iiv.agent.es.SocketLogEsGateway; +import me.iiv.agent.mcp.McpErrorCode; +import me.iiv.agent.mcp.ToolCallException; +import me.iiv.agent.mcp.ToolObject; +import me.iiv.agent.mcp.XqTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ai.tool.annotation.Tool; +import org.springframework.ai.tool.annotation.ToolParam; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.YearMonth; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeFormatterBuilder; +import java.time.format.DateTimeParseException; +import java.time.format.ResolverStyle; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 出纸机通信日志查询工具,对应老系统 SocketLogController /hardwareLog/listByPage。 + * 关键语义:月别名 socket_log_yyyyMM;集群由 Redis Dictionary.SocketLogPath 决定 + * (offline=本地集群,其余/缺失=云集群)。按 2026-11-30 王恒拍板:不施加行级 ACL、 + * 允许服务 Token、时间范围必须同月、索引不存在返回空 + notice。 + * 设计文档:doc/socket-log-list-mcp-design.md + */ +@Component +public class SocketLogTools implements ToolObject { + + private static final Logger log = LoggerFactory.getLogger(SocketLogTools.class); + + private static final int DEFAULT_ROWS = 20; + private static final int MAX_ROWS = 100; + /** ES from+size 深分页上限 max_result_window */ + private static final int MAX_RESULT_WINDOW = 10000; + private static final String INDEX_PREFIX = "socket_log_"; + private static final String DICTIONARY_KEY = "Dictionary"; + private static final String DICT_SOCKET_LOG_PATH = "SocketLogPath"; + private static final int MAX_SN_LENGTH = 64; + + private static final ZoneId SHANGHAI = ZoneId.of("Asia/Shanghai"); + private static final DateTimeFormatter DATE = new DateTimeFormatterBuilder() + .appendPattern("uuuu-MM-dd").toFormatter().withResolverStyle(ResolverStyle.STRICT); + private static final DateTimeFormatter DATE_TIME = new DateTimeFormatterBuilder() + .appendPattern("uuuu-MM-dd HH:mm:ss").toFormatter().withResolverStyle(ResolverStyle.STRICT); + private static final DateTimeFormatter INDEX_MONTH = DateTimeFormatter.ofPattern("yyyyMM"); + + /** 老系统 TypeToNameUtils.getLogTypeName 的完整取值域(Swagger 只列到 14,实际还有 15-18、99) */ + private static final Set LOG_TYPES = Set.of( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 99); + + final SocketLogEsGateway gateway; + final StringRedisTemplate redisTemplate; + + public SocketLogTools(SocketLogEsGateway gateway, StringRedisTemplate redisTemplate) { + this.gateway = gateway; + this.redisTemplate = redisTemplate; + } + + @XqTool(category = "hardware", kind = "read") + @Tool(name = "hardware.socketlog.list.query", description = "出纸机通信日志分页查询(ES socket_log_yyyyMM 月索引," + + "对应老系统 /hardwareLog/listByPage)。snCode 必填;logType 多选" + + "(0=下上线 1=出纸 2=rfid 3=报警 4=错误 5=有人无人 6=背景值检测 7=锁 8=上纸动作 9=设备升级 " + + "10=设备心跳 11=出纸开关 12=出纸口清理 13=出纸模式设定 14=设置亮灯响铃模式 15=工程模式设定 " + + "16=自由指令 17=三挡纸量检测 18=更改设备类型 99=未知指令),不传=全部;" + + "startTime/endTime 可选,支持 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss,必须同时传或同时不传、" + + "且必须为同一个自然月,都不传=查当天;按 createTime 倒序。" + + "集群由 Redis Dictionary.SocketLogPath 决定(offline=本地,其余=云),返回 cluster/index。" + + "不施加行级 ACL(对齐老接口);索引不存在返回空结果 + notice。" + + "page 默认 1,rows 默认 20、上限 100(超出截断)。") + public Map hardwareSocketLogListQuery( + @ToolParam(description = "设备 SN,必填,非空,最长 64 字符,match_phrase 精确短语匹配") String snCode, + @ToolParam(required = false, description = "日志类型多选,允许 0-18、99;不传=全部") List logType, + @ToolParam(required = false, description = "开始时间,yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss,含;" + + "与 endTime 必须同时传或同时不传,且必须为同一个自然月") String startTime, + @ToolParam(required = false, description = "结束时间,yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss,含;" + + "只传日期时自动补 23:59:59") String endTime, + @ToolParam(required = false, description = "页码,从 1 开始,默认 1") Integer page, + @ToolParam(required = false, description = "每页条数,默认 20,上限 100(超出截断为 100)") Integer rows) { + String sn = snCode == null ? null : snCode.trim(); + if (!StringUtils.hasText(sn)) { + throw invalid("snCode 必填,非空"); + } + if (sn.length() > MAX_SN_LENGTH) { + throw invalid("snCode 最长 " + MAX_SN_LENGTH + " 字符"); + } + List logTypes = normalizeLogTypes(logType); + + LocalDateTime start; + LocalDateTime end; + String startText = trimToNull(startTime); + String endText = trimToNull(endTime); + if ((startText == null) != (endText == null)) { + throw invalid("startTime 与 endTime 必须同时传或同时不传"); + } + if (startText == null) { + LocalDate today = LocalDate.now(SHANGHAI); + start = today.atStartOfDay(); + end = today.atTime(23, 59, 59); + } else { + start = parseStart(startText); + end = parseEnd(endText); + } + if (start.isAfter(end)) { + throw invalid("startTime 不能晚于 endTime"); + } + if (!YearMonth.from(start).equals(YearMonth.from(end))) { + // 老接口跨月只查开始月、静默丢结束月数据;这里显式拒绝 + throw invalid("startTime 与 endTime 必须为同一个自然月(月索引 socket_log_yyyyMM 按开始月选择)"); + } + + int pageNo = page == null || page < 1 ? 1 : page; + boolean truncatedRows = rows != null && rows > MAX_ROWS; + int pageSize = rows == null || rows < 1 ? DEFAULT_ROWS : Math.min(rows, MAX_ROWS); + long fromLong = (long) (pageNo - 1) * pageSize; + String windowNotice = null; + if (fromLong >= MAX_RESULT_WINDOW) { + // from+size 超出 ES max_result_window 会被 ES 拒绝,截断为窗口内最后可用的完整页 + fromLong = MAX_RESULT_WINDOW - pageSize; + windowNotice = "查询起始位置超过 ES max_result_window(10000),已截断为第 " + + (fromLong / pageSize + 1) + " 页起的最后可用窗口"; + } else if (fromLong + pageSize > MAX_RESULT_WINDOW) { + windowNotice = "本页超出 ES max_result_window(10000),已截断为 " + (MAX_RESULT_WINDOW - fromLong) + " 条"; + pageSize = MAX_RESULT_WINDOW - (int) fromLong; + } + + boolean localCluster = useLocalCluster(); + String index = INDEX_PREFIX + INDEX_MONTH.format(start); + + SocketLogEsGateway.Result search; + try { + search = gateway.search(localCluster, index, sn, logTypes, + toEpochMillis(start), toEpochMillis(end), (int) fromLong, pageSize); + } catch (IllegalStateException e) { + log.error("查询出纸机通信日志失败: {}", e.getMessage()); + throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE, "ES 查询通信日志失败,请稍后重试"); + } + + List> records = new ArrayList<>(); + for (SocketLogEsGateway.Record record : search.getRecords()) { + records.add(toRecord(record)); + } + + Map result = new LinkedHashMap<>(); + result.put("snCode", sn); + result.put("cluster", localCluster ? "local" : "cloud"); + result.put("index", index); + result.put("total", search.getTotal()); + result.put("totalPages", search.getTotal() == 0 ? 0L : (search.getTotal() + pageSize - 1) / pageSize); + result.put("page", pageNo); + result.put("rows", pageSize); + String notice = notice(truncatedRows, windowNotice, + search.isIndexMissing() + ? "该月索引 " + index + " 在当前集群(" + (localCluster ? "local" : "cloud") + + ")不存在,返回空结果" + : null); + if (notice != null) { + result.put("notice", notice); + } + result.put("records", records); + return result; + } + + private boolean useLocalCluster() { + Object value; + try { + value = redisTemplate.opsForHash().get(DICTIONARY_KEY, DICT_SOCKET_LOG_PATH); + } catch (RuntimeException e) { + log.error("读取 Redis Dictionary.SocketLogPath 失败: {}", e.getMessage()); + throw new ToolCallException(McpErrorCode.UPSTREAM_UNAVAILABLE, "Redis 字典暂不可用,请稍后重试"); + } + // 老接口口径:只有 offline 走本地集群,其余(含 key 不存在)走云集群 + return value != null && "offline".equals(String.valueOf(value)); + } + + private static List normalizeLogTypes(List values) { + if (values == null || values.isEmpty()) { + return null; + } + Set distinct = new LinkedHashSet<>(); + for (Integer value : values) { + if (value == null) { + throw invalid("logType 不能包含空值"); + } + if (!LOG_TYPES.contains(value)) { + throw invalid("logType 仅支持 0-18、99,非法值: " + value); + } + distinct.add(value); + } + return new ArrayList<>(distinct); + } + + private Map toRecord(SocketLogEsGateway.Record log) { + Map record = new LinkedHashMap<>(); + record.put("id", log.getId()); + record.put("createId", log.getCreateId()); + record.put("createTime", log.getCreateTime()); + record.put("modifyId", log.getModifyId()); + record.put("modifyTime", log.getModifyTime()); + record.put("softDelete", log.getSoftDelete()); + record.put("snCode", log.getSnCode()); + record.put("buildingId", log.getBuildingId()); + record.put("districtId", log.getDistrictId()); + record.put("propertyId", log.getPropertyId()); + record.put("agentId", log.getAgentId()); + record.put("logType", log.getLogType()); + record.put("logTypeText", logTypeText(log.getLogType())); + record.put("logContent", log.getLogContent()); + record.put("useType", log.getUseType()); + record.put("useTypeText", useTypeText(log.getUseType())); + record.put("messageType", log.getMessageType()); + record.put("messageTypeText", messageTypeText(log.getMessageType())); + // 按拍板不截断;原始通信内容可能较长,由调用方自行处理 + record.put("srcLogContent", log.getSrcLogContent()); + record.put("tableName", log.getTableName()); + return record; + } + + private static String notice(boolean truncatedRows, String windowNotice, String indexNotice) { + StringBuilder builder = new StringBuilder(); + append(builder, truncatedRows ? "rows 超过上限 100,已截断为 100" : null); + append(builder, windowNotice); + append(builder, indexNotice); + return builder.length() == 0 ? null : builder.toString(); + } + + private static void append(StringBuilder builder, String part) { + if (part == null) { + return; + } + if (builder.length() > 0) { + builder.append(";"); + } + builder.append(part); + } + + private static String logTypeText(Integer value) { + if (value == null) { + return null; + } + return switch (value) { + case 0 -> "下上线"; + case 1 -> "出纸"; + case 2 -> "rfid"; + case 3 -> "报警"; + case 4 -> "错误"; + case 5 -> "有人无人"; + case 6 -> "背景值检测"; + case 7 -> "锁"; + case 8 -> "上纸动作"; + case 9 -> "设备升级"; + case 10 -> "设备心跳"; + case 11 -> "出纸开关"; + case 12 -> "出纸口清理"; + case 13 -> "出纸模式设定"; + case 14 -> "设置亮灯响铃模式"; + case 15 -> "工程模式设定"; + case 16 -> "自由指令"; + case 17 -> "三挡纸量检测"; + case 18 -> "更改设备类型"; + case 99 -> "未知指令"; + default -> "未知(" + value + ")"; + }; + } + + private static String messageTypeText(Integer value) { + if (value == null) { + return null; + } + return switch (value) { + case 0 -> "上行"; + case 1 -> "下行"; + default -> "未知(" + value + ")"; + }; + } + + private static String useTypeText(Integer value) { + if (value == null) { + return null; + } + return switch (value) { + case 0 -> "运维"; + case 1 -> "普通人员"; + default -> "未知(" + value + ")"; + }; + } + + private static LocalDateTime parseStart(String value) { + if (value.length() == 10) { + return parseDate(value, "startTime").atStartOfDay(); + } + return parseDateTime(value, "startTime"); + } + + private static LocalDateTime parseEnd(String value) { + if (value.length() == 10) { + return parseDate(value, "endTime").atTime(23, 59, 59); + } + return parseDateTime(value, "endTime"); + } + + private static LocalDate parseDate(String value, String name) { + try { + return LocalDate.parse(value, DATE); + } catch (DateTimeParseException e) { + throw invalid(name + " 格式非法,要求 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss: " + value); + } + } + + private static LocalDateTime parseDateTime(String value, String name) { + try { + return LocalDateTime.parse(value, DATE_TIME); + } catch (DateTimeParseException e) { + throw invalid(name + " 格式非法,要求 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss: " + value); + } + } + + private static long toEpochMillis(LocalDateTime value) { + return value.atZone(SHANGHAI).toInstant().toEpochMilli(); + } + + private static String trimToNull(String value) { + return StringUtils.hasText(value) ? value.trim() : null; + } + + private static ToolCallException invalid(String message) { + return new ToolCallException(McpErrorCode.INVALID_ARGUMENT, message); + } +} diff --git a/xiaoqu-agent-service/src/test/java/me/iiv/agent/es/SocketLogEsGatewayImplTest.java b/xiaoqu-agent-service/src/test/java/me/iiv/agent/es/SocketLogEsGatewayImplTest.java new file mode 100644 index 0000000..5b3e6a7 --- /dev/null +++ b/xiaoqu-agent-service/src/test/java/me/iiv/agent/es/SocketLogEsGatewayImplTest.java @@ -0,0 +1,245 @@ +package me.iiv.agent.es; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.http.HttpHost; +import org.apache.http.HttpVersion; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.message.BasicHttpRequest; +import org.apache.http.message.BasicStatusLine; +import org.apache.http.util.EntityUtils; +import org.elasticsearch.client.Request; +import org.elasticsearch.client.Response; +import org.elasticsearch.client.ResponseException; +import org.elasticsearch.client.RestClient; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.io.IOException; +import java.util.List; + +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.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class SocketLogEsGatewayImplTest { + + private static final String RESPONSE_JSON = "{" + + "\"took\":1,\"timed_out\":false," + + "\"_shards\":{\"total\":1,\"successful\":1,\"skipped\":0,\"failed\":0}," + + "\"hits\":{\"total\":{\"value\":2,\"relation\":\"eq\"}," + + "\"hits\":[" + + "{\"_index\":\"socket_log_20261104\",\"_source\":{" + + "\"id\":-4159793239005902279,\"createId\":0,\"createTime\":\"2026-11-25T10:30:42+08:00\"," + + "\"modifyId\":395,\"modifyTime\":\"2026-11-25T10:31:00+08:00\",\"softDelete\":0," + + "\"snCode\":\"X1A1100800000007\",\"buildingId\":42,\"districtId\":3,\"propertyId\":1," + + "\"agentId\":17,\"logType\":0,\"logContent\":\"设备上线\",\"useType\":1,\"messageType\":0," + + "\"srcLogContent\":\"X1A1100800000007:up===LK;===SRC:LK,0;\",\"tableName\":\"socket_log_20261125\"}}," + + "{\"_source\":{\"id\":123,\"createTime\":1795536000000,\"logType\":\"99\",\"messageType\":\"1\"}}" + + "]}}"; + + @Mock + RestClient cloudRestClient; + @Mock + RestClient localRestClient; + + SocketLogEsGatewayImpl gateway; + + private final ObjectMapper mapper = new ObjectMapper(); + + @BeforeEach + void setUp() { + gateway = new SocketLogEsGatewayImpl(cloudRestClient, localRestClient); + } + + private static Response esResponse(String jsonBody) { + Response response = mock(Response.class); + when(response.getEntity()).thenReturn(new StringEntity(jsonBody, ContentType.APPLICATION_JSON)); + return response; + } + + private JsonNode captureRequestBody(boolean localCluster, List logTypes) throws Exception { + Response response = esResponse(RESPONSE_JSON); + when((localCluster ? localRestClient : cloudRestClient).performRequest(any(Request.class))) + .thenReturn(response); + gateway.search(localCluster, "socket_log_202611", "X1A1100800000007", logTypes, + 1795536000000L, 1795622399000L, 40, 20); + RestClient client = localCluster ? localRestClient : cloudRestClient; + ArgumentCaptor captor = ArgumentCaptor.forClass(Request.class); + verify(client).performRequest(captor.capture()); + Request captured = captor.getValue(); + assertEquals("POST", captured.getMethod()); + assertEquals("/socket_log_202611/_search", captured.getEndpoint()); + return mapper.readTree(EntityUtils.toString(captured.getEntity())); + } + + private static boolean anyFilter(JsonNode filters, java.util.function.Predicate predicate) { + for (JsonNode filter : filters) { + if (predicate.test(filter)) { + return true; + } + } + return false; + } + + @Test + void buildsMatchPhraseTermsRangeSortAndPagination() throws Exception { + JsonNode body = captureRequestBody(false, List.of(0, 2)); + + assertEquals(40, body.get("from").asInt()); + assertEquals(20, body.get("size").asInt()); + assertTrue(body.get("track_total_hits").asBoolean()); + // createTime DESC + id DESC(老接口只有 createTime,加 id 保证分页稳定) + assertEquals("desc", body.at("/sort/0/createTime/order").asText()); + assertEquals("desc", body.at("/sort/1/id/order").asText()); + + JsonNode filters = body.at("/query/bool/filter"); + assertTrue(anyFilter(filters, f -> f.has("match_phrase") + && f.get("match_phrase").get("snCode").get("query").asText().equals("X1A1100800000007"))); + assertTrue(anyFilter(filters, f -> f.has("terms") + && f.get("terms").get("logType").toString().equals("[0,2]"))); + // date 字段 range 必须发 epoch 毫秒 + assertTrue(anyFilter(filters, f -> f.has("range") + && f.get("range").get("createTime").get("gte").asLong() == 1795536000000L + && f.get("range").get("createTime").get("lte").asLong() == 1795622399000L)); + // 不施加行级 ACL:bool 里不应出现 should + assertFalse(body.at("/query/bool").has("should")); + } + + @Test + void omitsTermsWhenLogTypesNull() throws Exception { + JsonNode body = captureRequestBody(false, null); + for (JsonNode filter : body.at("/query/bool/filter")) { + assertTrue(!filter.has("terms") || filter.get("terms").findValue("logType") == null); + } + } + + @Test + void omitsTermsWhenLogTypesEmpty() throws Exception { + JsonNode body = captureRequestBody(false, List.of()); + for (JsonNode filter : body.at("/query/bool/filter")) { + assertTrue(!filter.has("terms") || filter.get("terms").findValue("logType") == null); + } + } + + @Test + void routesToClusterClient() throws Exception { + captureRequestBody(true, null); + verify(localRestClient).performRequest(any(Request.class)); + verify(cloudRestClient, never()).performRequest(any(Request.class)); + } + + @Test + void mapsHitsAndNormalizesTime() throws IOException { + Response response = esResponse(RESPONSE_JSON); + when(cloudRestClient.performRequest(any(Request.class))).thenReturn(response); + + SocketLogEsGateway.Result result = gateway.search(false, "socket_log_202611", + "X1A1100800000007", List.of(0), 1795536000000L, 1795622399000L, 0, 20); + + assertEquals(2, result.getTotal()); + assertFalse(result.isIndexMissing()); + SocketLogEsGateway.Record first = result.getRecords().get(0); + assertEquals(Long.valueOf(-4159793239005902279L), first.getId()); + assertEquals(Long.valueOf(0L), first.getCreateId()); + assertEquals("2026-11-25 10:30:42", first.getCreateTime()); + assertEquals(Long.valueOf(395L), first.getModifyId()); + assertEquals("2026-11-25 10:31:00", first.getModifyTime()); + assertEquals(Integer.valueOf(0), first.getSoftDelete()); + assertEquals("X1A1100800000007", first.getSnCode()); + assertEquals(Long.valueOf(42L), first.getBuildingId()); + assertEquals(Long.valueOf(3L), first.getDistrictId()); + assertEquals(Long.valueOf(1L), first.getPropertyId()); + assertEquals(Long.valueOf(17L), first.getAgentId()); + assertEquals(Integer.valueOf(0), first.getLogType()); + assertEquals("设备上线", first.getLogContent()); + assertEquals(Integer.valueOf(1), first.getUseType()); + assertEquals(Integer.valueOf(0), first.getMessageType()); + assertEquals("X1A1100800000007:up===LK;===SRC:LK,0;", first.getSrcLogContent()); + assertEquals("socket_log_20261125", first.getTableName()); + // epoch 毫秒形态归一为 Asia/Shanghai 文本;文本型数值("99"/"1")也要能解析 + assertEquals("2026-11-25 00:00:00", result.getRecords().get(1).getCreateTime()); + assertEquals(Integer.valueOf(99), result.getRecords().get(1).getLogType()); + assertEquals(Integer.valueOf(1), result.getRecords().get(1).getMessageType()); + } + + @Test + void mapsMissingFieldsAsNull() throws IOException { + String response = "{\"hits\":{\"total\":{\"value\":1,\"relation\":\"eq\"}," + + "\"hits\":[{\"_source\":{}}]}}"; + Response esResponse = esResponse(response); + when(cloudRestClient.performRequest(any(Request.class))).thenReturn(esResponse); + + SocketLogEsGateway.Record record = gateway.search(false, "socket_log_202611", + "SN", null, 0L, 1L, 0, 20).getRecords().get(0); + + assertNull(record.getId()); + assertNull(record.getCreateTime()); + assertNull(record.getLogType()); + assertNull(record.getSrcLogContent()); + } + + @Test + void returnsEmptyResultWhenIndexNotFound() throws IOException { + Response missingIndex = mock(Response.class); + when(missingIndex.getRequestLine()) + .thenReturn(new BasicHttpRequest("POST", "/socket_log_202610/_search").getRequestLine()); + when(missingIndex.getHost()).thenReturn(new HttpHost("localhost", 9200)); + when(missingIndex.getStatusLine()) + .thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not Found")); + when(missingIndex.getEntity()).thenReturn(new StringEntity( + "{\"error\":{\"type\":\"index_not_found_exception\",\"reason\":\"no such index\"}," + + "\"status\":404}", ContentType.APPLICATION_JSON)); + ResponseException responseException = new ResponseException(missingIndex); + when(cloudRestClient.performRequest(any(Request.class))).thenThrow(responseException); + + SocketLogEsGateway.Result result = gateway.search(false, "socket_log_202610", + "SN", null, 0L, 1L, 0, 20); + + assertEquals(0, result.getTotal()); + assertTrue(result.getRecords().isEmpty()); + assertTrue(result.isIndexMissing()); + } + + @Test + void wrapsOtherResponseErrorsInIllegalState() throws IOException { + Response serverError = mock(Response.class); + when(serverError.getRequestLine()) + .thenReturn(new BasicHttpRequest("POST", "/socket_log_202611/_search").getRequestLine()); + when(serverError.getHost()).thenReturn(new HttpHost("localhost", 9200)); + when(serverError.getStatusLine()) + .thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 500, "Internal Server Error")); + when(serverError.getEntity()).thenReturn(new StringEntity( + "{\"error\":{\"type\":\"search_phase_execution_exception\"},\"status\":500}", + ContentType.APPLICATION_JSON)); + ResponseException responseException = new ResponseException(serverError); + when(cloudRestClient.performRequest(any(Request.class))).thenThrow(responseException); + + IllegalStateException exception = assertThrows(IllegalStateException.class, + () -> gateway.search(false, "socket_log_202611", "SN", null, 0L, 1L, 0, 20)); + assertTrue(exception.getMessage().startsWith("ES 查询通信日志失败")); + } + + @Test + void wrapsIoFailureInIllegalState() throws IOException { + when(cloudRestClient.performRequest(any(Request.class))) + .thenThrow(new IOException("connection reset")); + + IllegalStateException exception = assertThrows(IllegalStateException.class, + () -> gateway.search(false, "socket_log_202611", "SN", null, 0L, 1L, 0, 20)); + assertTrue(exception.getMessage().startsWith("ES 查询通信日志失败")); + } +} diff --git a/xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/SocketLogToolsTest.java b/xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/SocketLogToolsTest.java new file mode 100644 index 0000000..090bd6f --- /dev/null +++ b/xiaoqu-agent-service/src/test/java/me/iiv/agent/mcp/tool/SocketLogToolsTest.java @@ -0,0 +1,330 @@ +package me.iiv.agent.mcp.tool; + +import me.iiv.agent.es.SocketLogEsGateway; +import me.iiv.agent.mcp.McpErrorCode; +import me.iiv.agent.mcp.ToolCallException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.StringRedisTemplate; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.YearMonth; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +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.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class SocketLogToolsTest { + + private static final ZoneId SH = ZoneId.of("Asia/Shanghai"); + private static final DateTimeFormatter INDEX_MONTH = DateTimeFormatter.ofPattern("yyyyMM"); + + @Mock + SocketLogEsGateway gateway; + @Mock + StringRedisTemplate redisTemplate; + @Mock + HashOperations hashOperations; + + SocketLogTools tools; + + @BeforeEach + void setUp() { + lenient().when(redisTemplate.opsForHash()).thenReturn(hashOperations); + tools = new SocketLogTools(gateway, redisTemplate); + } + + private void stubEmpty() { + when(gateway.search(anyBoolean(), anyString(), anyString(), any(), anyLong(), anyLong(), anyInt(), anyInt())) + .thenReturn(new SocketLogEsGateway.Result(0, List.of(), false)); + } + + private static long millis(String dateTime) { + return LocalDateTime.parse(dateTime).atZone(SH).toInstant().toEpochMilli(); + } + + @Test + void defaultsToTodayCloudClusterAndCurrentMonthIndex() { + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn("online"); + stubEmpty(); + + Map result = tools.hardwareSocketLogListQuery(" SN-1 ", null, null, null, null, null); + + LocalDate today = LocalDate.now(SH); + assertEquals("SN-1", result.get("snCode")); + assertEquals("cloud", result.get("cluster")); + assertEquals("socket_log_" + today.format(INDEX_MONTH), result.get("index")); + assertEquals(0L, result.get("total")); + assertEquals(0L, result.get("totalPages")); + assertEquals(1, result.get("page")); + assertEquals(20, result.get("rows")); + assertFalse(result.containsKey("notice")); + verify(gateway).search(eq(false), eq("socket_log_" + today.format(INDEX_MONTH)), eq("SN-1"), + isNull(), eq(millis(today + "T00:00:00")), eq(millis(today + "T23:59:59")), eq(0), eq(20)); + } + + @Test + void offlineDictionaryRoutesToLocalCluster() { + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn("offline"); + stubEmpty(); + + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20); + + assertEquals("local", result.get("cluster")); + verify(gateway).search(eq(true), anyString(), anyString(), isNull(), anyLong(), anyLong(), eq(0), eq(20)); + } + + @Test + void missingOrUnknownDictionaryFallsBackToCloud() { + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn(null); + stubEmpty(); + + assertEquals("cloud", tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20).get("cluster")); + + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn("online"); + assertEquals("cloud", tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20).get("cluster")); + } + + @Test + void passesLogTypesAndExplicitRange() { + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn("offline"); + stubEmpty(); + + tools.hardwareSocketLogListQuery("SN-1", Arrays.asList(2, 99, 2), "2026-11-01", "2026-11-30", 2, 50); + + verify(gateway).search(eq(true), eq("socket_log_202611"), eq("SN-1"), eq(List.of(2, 99)), + eq(millis("2026-11-01T00:00:00")), eq(millis("2026-11-30T23:59:59")), eq(50), eq(50)); + } + + @Test + void acceptsDateTimeAndNormalizesBounds() { + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn("offline"); + stubEmpty(); + + tools.hardwareSocketLogListQuery("SN-1", null, "2026-11-01 08:00:00", "2026-11-01 09:00:00", 1, 20); + + verify(gateway).search(anyBoolean(), eq("socket_log_202611"), anyString(), isNull(), + eq(millis("2026-11-01T08:00:00")), eq(millis("2026-11-01T09:00:00")), eq(0), eq(20)); + } + + @Test + void rejectsInvalidArguments() { + // snCode 为空 / 超长 + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery(" ", null, null, null, 1, 20)); + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery("A".repeat(65), null, null, null, 1, 20)); + // 只传一个时间 + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", null, "2026-11-01", null, 1, 20)); + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", null, null, "2026-11-30", 1, 20)); + // 格式非法 + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", null, "2026/11/01", "2026-11-30", 1, 20)); + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", null, "2026-11-01", "2026-11-30 9:00:00", 1, 20)); + // start > end + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", null, "2026-11-30", "2026-11-01", 1, 20)); + // 跨月(老接口静默丢数据,这里显式拒绝) + ToolCallException crossMonth = assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", null, "2026-11-01", "2026-12-01", 1, 20)); + assertTrue(crossMonth.getRawMessage().contains("同一个自然月")); + // logType 非法 + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", List.of(19), null, null, 1, 20)); + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", List.of(-1), null, null, 1, 20)); + assertThrows(ToolCallException.class, () -> tools.hardwareSocketLogListQuery( + "SN-1", Arrays.asList(1, null), null, null, 1, 20)); + verifyNoInteractions(gateway); + } + + @Test + void invalidArgumentUsesInvalidArgumentCode() { + ToolCallException exception = assertThrows(ToolCallException.class, + () -> tools.hardwareSocketLogListQuery(" ", null, null, null, 1, 20)); + assertEquals(McpErrorCode.INVALID_ARGUMENT, exception.getCode()); + } + + @Test + void truncatesRowsOverMaxWithNotice() { + stubEmpty(); + + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 500); + + assertEquals(100, result.get("rows")); + assertEquals("rows 超过上限 100,已截断为 100", result.get("notice")); + verify(gateway).search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), eq(0), eq(100)); + } + + @Test + void fallsBackToDefaultsForInvalidPageAndRows() { + stubEmpty(); + + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 0, -1); + + assertEquals(1, result.get("page")); + assertEquals(20, result.get("rows")); + verify(gateway).search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), eq(0), eq(20)); + } + + @Test + void truncatesWindowWhenFromExceedsMaxResultWindow() { + stubEmpty(); + + // from = 500*20 = 10000 ≥ 10000 → 截断为最后可用窗口 9980,即第 500 页 + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 501, 20); + + assertEquals(501, result.get("page")); + assertEquals(20, result.get("rows")); + assertEquals("查询起始位置超过 ES max_result_window(10000),已截断为第 500 页起的最后可用窗口", + result.get("notice")); + verify(gateway).search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), eq(9980), eq(20)); + } + + @Test + void truncatesPartialPageWithinMaxResultWindow() { + stubEmpty(); + + // from = 166*60 = 9960 < 10000,但 9960+60 > 10000 → 本页截断为 40 条 + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 167, 60); + + assertEquals(40, result.get("rows")); + assertEquals("本页超出 ES max_result_window(10000),已截断为 40 条", result.get("notice")); + verify(gateway).search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), eq(9960), eq(40)); + } + + @Test + void indexMissingReturnsEmptyWithNotice() { + when(gateway.search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), anyInt(), anyInt())) + .thenReturn(new SocketLogEsGateway.Result(0, List.of(), true)); + + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20); + + assertEquals(0L, result.get("total")); + assertEquals(0L, result.get("totalPages")); + assertEquals("该月索引 socket_log_" + YearMonth.now(SH).format(INDEX_MONTH) + + " 在当前集群(cloud)不存在,返回空结果", result.get("notice")); + } + + @Test + @SuppressWarnings("unchecked") + void mapsRecordsAndComputesTotalPages() { + when(gateway.search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), anyInt(), anyInt())) + .thenReturn(new SocketLogEsGateway.Result(41, List.of( + record(0, 0, 0), record(2, 0, 1), record(16, 0, 1), + record(99, 1, 0), record(null, null, null)), false)); + + Map result = tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20); + + assertEquals(41L, result.get("total")); + // 41 条 / 每页 20 → 3 页 + assertEquals(3L, result.get("totalPages")); + List> records = (List>) result.get("records"); + assertEquals(5, records.size()); + Map first = records.get(0); + assertEquals(1L, first.get("id")); + assertEquals("2026-11-01 00:00:00", first.get("createTime")); + assertEquals("2026-11-01 00:01:00", first.get("modifyTime")); + assertEquals("SN-1", first.get("snCode")); + assertEquals(0, first.get("logType")); + assertEquals("下上线", first.get("logTypeText")); + assertEquals("设备上线", first.get("logContent")); + assertEquals(0, first.get("messageType")); + assertEquals("上行", first.get("messageTypeText")); + assertEquals(0, first.get("useType")); + assertEquals("运维", first.get("useTypeText")); + assertEquals("SRC-0", first.get("srcLogContent")); + assertEquals("socket_log_20261101", first.get("tableName")); + + assertEquals(Arrays.asList("下上线", "rfid", "自由指令", "未知指令", null), + records.stream().map(r -> r.get("logTypeText")).collect(Collectors.toList())); + assertEquals(Arrays.asList("上行", "上行", "上行", "下行", null), + records.stream().map(r -> r.get("messageTypeText")).collect(Collectors.toList())); + } + + @Test + void redisFailureMapsToUpstreamUnavailable() { + when(redisTemplate.opsForHash()).thenThrow(new IllegalStateException("redis down")); + + ToolCallException exception = assertThrows(ToolCallException.class, + () -> tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20)); + assertEquals(McpErrorCode.UPSTREAM_UNAVAILABLE, exception.getCode()); + verifyNoInteractions(gateway); + } + + @Test + void gatewayFailureMapsToUpstreamUnavailable() { + when(hashOperations.get("Dictionary", "SocketLogPath")).thenReturn("online"); + when(gateway.search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), anyInt(), anyInt())) + .thenThrow(new IllegalStateException("ES timeout")); + + ToolCallException exception = assertThrows(ToolCallException.class, + () -> tools.hardwareSocketLogListQuery("SN-1", null, null, null, 1, 20)); + assertEquals(McpErrorCode.UPSTREAM_UNAVAILABLE, exception.getCode()); + } + + @Test + void springAiPublishesToolSchema() { + var callbacks = org.springframework.ai.tool.method.MethodToolCallbackProvider.builder() + .toolObjects(tools).build().getToolCallbacks(); + Map schemas = Arrays.stream(callbacks).collect(Collectors.toMap( + callback -> callback.getToolDefinition().name(), + callback -> callback.getToolDefinition().inputSchema())); + + assertEquals(1, schemas.size()); + assertTrue(schemas.containsKey("hardware.socketlog.list.query")); + assertTrue(schemas.get("hardware.socketlog.list.query").contains("snCode")); + assertTrue(schemas.get("hardware.socketlog.list.query").contains("logType")); + } + + private static SocketLogEsGateway.Record record(Integer logType, Integer messageType, Integer useType) { + return new SocketLogEsGateway.Record(1L, 9L, "2026-11-01 00:00:00", 10L, "2026-11-01 00:01:00", + 0, "SN-1", 42L, 3L, 1L, 17L, logType, "设备上线", useType, messageType, + "SRC-" + (logType == null ? "null" : logType), "socket_log_20261101"); + } + + @Test + void keepsNullRecordFieldsAsIs() { + SocketLogEsGateway.Record record = new SocketLogEsGateway.Record(null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null); + when(gateway.search(anyBoolean(), anyString(), anyString(), isNull(), anyLong(), anyLong(), anyInt(), anyInt())) + .thenReturn(new SocketLogEsGateway.Result(1, List.of(record), false)); + + @SuppressWarnings("unchecked") + Map row = ((List>) tools.hardwareSocketLogListQuery( + "SN-1", null, null, null, 1, 20).get("records")).get(0); + + assertNull(row.get("id")); + assertNull(row.get("createTime")); + assertNull(row.get("logType")); + assertNull(row.get("logTypeText")); + assertNull(row.get("messageTypeText")); + assertNull(row.get("useTypeText")); + } +}