设备的部分改造
All checks were successful
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Successful in 7m34s

This commit is contained in:
2026-03-10 10:34:08 +08:00
parent 86f8d0b644
commit b5147d1acb
34 changed files with 1680 additions and 485 deletions

View File

@@ -0,0 +1,54 @@
## Why
当前 `internal/gateway/` 包只是一个薄 HTTP 客户端包装,每个方法手动构建 `map[string]interface{}` 参数、手动 unmarshal 响应,代码高度重复。更严重的是 Handler 层(`iot_card.go` 6 处、`device.go` 7 处)直接调用 `gateway.Client` 跳过了 Service 层,违反了项目 `Handler → Service → Store → Model` 的分层架构。此外缺少请求/响应日志和重试机制,排查问题困难,网络抖动直接导致失败。
## What Changes
### Gateway 包内部重构
- **消除手动 map 构建**:请求结构体直接序列化,不再手动构建 `map[string]interface{}`
- **泛型响应解析**:提供泛型方法统一处理 `doRequest + unmarshal` 模式,消除每个方法的重复 unmarshal 代码
- **添加请求/响应日志**:在 `doRequest` 中集成 Zap 日志,记录请求路径、参数摘要、响应状态、耗时等关键信息
- **添加重试机制**对网络级错误连接失败、DNS 解析失败、超时)自动重试,业务错误不重试;默认最多重试 2 次,指数退避
- **验证响应模型**:对照 Gateway 上游源码验证 `DeviceInfoResp``SlotInfoResp` 等响应结构的字段准确性
### 分层架构修复(**BREAKING**
- **IotCard Handler 的 6 个 Gateway 直接调用下沉到 IotCard Service 层**`QueryCardStatus``QueryFlow``QueryRealnameStatus``GetRealnameLink``StopCard``StartCard`
- **Device Handler 的 7 个 Gateway 直接调用下沉到 Device Service 层**`GetDeviceInfo``GetSlotInfo``SetSpeedLimit``SetWiFi``SwitchCard``RebootDevice``ResetDevice`
- Handler 层不再持有 `gateway.Client` 引用,所有 Gateway 调用通过 Service 层发起
### 不在本次范围
- 异步接口(`device/info``device/card-info`)的轮询/回调处理 — 暂不处理
- 新增 Gateway 端点封装 — 只重构已有的
## Capabilities
### New Capabilities
- `gateway-request-logging`: Gateway 请求/响应的日志记录能力,包括请求路径、参数摘要、响应状态码、耗时、错误信息
- `gateway-retry`: Gateway 网络级错误的自动重试能力,支持指数退避和可配置的重试次数
### Modified Capabilities
- `gateway-client`: 消除手动 map 构建、泛型响应解析、请求结构体直接序列化
- `iot-card`: IotCard Handler 中 6 个 Gateway 直接调用下沉到 Service 层Handler 不再持有 gateway.Client
- `iot-device`: Device Handler 中 7 个 Gateway 直接调用下沉到 Service 层Handler 不再持有 gateway.Client
## Impact
### 代码变更范围
- `internal/gateway/client.go` — 添加日志、重试、泛型方法
- `internal/gateway/device.go` — 消除 map 构建,使用泛型响应解析
- `internal/gateway/flow_card.go` — 消除 map 构建,使用泛型响应解析
- `internal/gateway/models.go` — 可能调整请求结构体(添加 JSON tag 使其可直接序列化)
- `internal/handler/admin/iot_card.go` — 移除 `gatewayClient` 依赖Gateway 调用改为调 Service
- `internal/handler/admin/device.go` — 移除 `gatewayClient` 依赖Gateway 调用改为调 Service
- `internal/service/iot_card/service.go` — 新增 6 个 Gateway 代理方法
- `internal/service/device/service.go` — 新增 7 个 Gateway 代理方法
- `internal/bootstrap/handlers.go` — Handler 初始化不再传入 gatewayClient
- `internal/bootstrap/services.go` — Service 初始化需确保 gatewayClient 注入
### API 影响
- 无 API 签名变更,前端无感知
- 行为上完全兼容,只是内部调用链路变更
### 依赖影响
- 新增 `go.uber.org/zap` 在 gateway 包中的依赖(项目已有)
- 无新外部依赖