feat: 实现工位终端滑动续签机制,强化安全与身份追溯
- 新增滑动续签功能:人工触屏触发本地心跳 + 30秒节流刷新JWT,避免作业中令牌过期 - 拆分质量检验权限:过程检/完工检使用不同权限码,细化权限粒度 - 新增操作人用户ID字段:报工、拧紧记录落库时携带可信用户ID,解决身份追溯问题 - 移除编译期默认密钥,启动期校验所有必要密钥非空,防止密钥泄露风险 - 修复WMS附件越权遍历问题:使用UUID文件名替代顺序ID访问附件 - 实现登录态过期数据隔离:仅返回当前操作人的待同步数据,避免身份混淆
This commit is contained in:
@@ -0,0 +1,264 @@
|
||||
package syncer_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bj_power_workstation/internal/mes"
|
||||
"bj_power_workstation/internal/store"
|
||||
"bj_power_workstation/internal/syncer"
|
||||
)
|
||||
|
||||
// 边界场景运行期验证(2026-10-06 简化模型):
|
||||
// 操作工手动点发送 → 用当前登录这人的身份 → 发不出去就是发不出去(留在本地 SQLite)。
|
||||
// 数据按 operator_id 隔离:仅当前登录人自己的未同步数据会被发送;
|
||||
// 其他人的数据不被代发、不对他人可见;同一人重新登录后可继续发送。
|
||||
|
||||
// captureServer 假 MES:记录每个请求的 Authorization 头,返回业务成功。
|
||||
type captureServer struct {
|
||||
mu sync.Mutex
|
||||
auth []string
|
||||
ts *httptest.Server
|
||||
}
|
||||
|
||||
func newCaptureServer() *captureServer {
|
||||
c := &captureServer{}
|
||||
c.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
c.mu.Lock()
|
||||
c.auth = append(c.auth, r.Header.Get("Authorization"))
|
||||
c.mu.Unlock()
|
||||
w.WriteHeader(200)
|
||||
_, _ = w.Write([]byte(`{"code":0,"message":"成功","data":null}`))
|
||||
}))
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *captureServer) count() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return len(c.auth)
|
||||
}
|
||||
|
||||
func (c *captureServer) lastAuth() string {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if len(c.auth) == 0 {
|
||||
return ""
|
||||
}
|
||||
return c.auth[len(c.auth)-1]
|
||||
}
|
||||
|
||||
// newTestEnv 开临时 SQLite + 假 MES + syncer。
|
||||
func newTestEnv(t *testing.T) (*store.Store, *mes.Client, *syncer.Syncer, *captureServer) {
|
||||
t.Helper()
|
||||
st, err := store.Open(t.TempDir() + "/ws.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
cap := newCaptureServer()
|
||||
t.Cleanup(cap.ts.Close)
|
||||
mc := mes.New(cap.ts.URL, "tok")
|
||||
return st, mc, syncer.New(st, mc), cap
|
||||
}
|
||||
|
||||
// 场景1(按操作人隔离 · 不代发):张三录入离线数据后离线,李四登录——
|
||||
// 李四的会话绝不能把张三的数据发出去(RunOnce=0、MES 未收到任何请求、数据保留在本地);
|
||||
// 张三重新登录后,自己的数据以张三当前有效 JWT 成功发出。
|
||||
func TestScenario1_OperatorIsolation(t *testing.T) {
|
||||
st, mc, sy, cap := newTestEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 张三登录(工位3,用户ID7)+ 离线录入 2 条
|
||||
if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang")
|
||||
for i := 0; i < 2; i++ {
|
||||
if err := st.InsertQueueItem("process_done", `{"sn":"SN-1-`+itoa(i)+`","operator":"张三"}`, 7, "张三"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// 李四登录(MES 网络恢复):张三的数据不被李四的会话代发
|
||||
if err := st.SaveStationSession("jwt_li", "li", "李四", 3, time.Now().Add(time.Hour).Unix(), 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_li")
|
||||
if n := sy.RunOnce(ctx); n != 0 {
|
||||
t.Fatalf("[场景1] 李四不应发送张三的数据,实际成功 %d 条", n)
|
||||
}
|
||||
if got := cap.count(); got != 0 {
|
||||
t.Errorf("[场景1] 李四会话不应向 MES 发出任何报工,实际发出 %d 次", got)
|
||||
}
|
||||
if n, _ := st.PendingQueueCount(); n != 2 {
|
||||
t.Errorf("[场景1] 张三的 2 条应原样保留,实际剩余 %d", n)
|
||||
}
|
||||
|
||||
// 张三重新登录:仅看到/发送自己的失败数据
|
||||
if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang2")
|
||||
if n := sy.RunOnce(ctx); n != 2 {
|
||||
t.Fatalf("[场景1] 张三重登后应成功发送 2 条,实际 %d", n)
|
||||
}
|
||||
if got := cap.lastAuth(); got != "Bearer jwt_zhang2" {
|
||||
t.Errorf("[场景1] 应以张三当前有效 JWT 发出,实际 %q", got)
|
||||
}
|
||||
if n, _ := st.PendingQueueCount(); n != 0 {
|
||||
t.Errorf("[场景1] 发送后队列应清空,实际剩余 %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景2(登出即暂停):张三登出 → 无登录人,任何数据都不发出(发不出去就是发不出去);
|
||||
// 重新登录(同一人)后数据还在,继续发送成功。
|
||||
func TestScenario2_LogoutPausesSending(t *testing.T) {
|
||||
st, mc, sy, cap := newTestEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 张三登录 + 离线录入
|
||||
if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang")
|
||||
if err := st.InsertQueueItem("temp_store", `{"sn":"SN-2","operator":"张三"}`, 7, "张三"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 张三登出(镜像 logoutHandler:清 session + 清当前 Bearer)
|
||||
if err := st.ClearStationSession(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("")
|
||||
if ss, err := st.GetStationSession(); err != nil || ss != nil {
|
||||
t.Fatalf("[场景2] 登出后登录态应清空,实际 ss=%+v err=%v", ss, err)
|
||||
}
|
||||
// 登出期间:不发送,数据留在本地
|
||||
if n := sy.RunOnce(ctx); n != 0 {
|
||||
t.Fatalf("[场景2] 登出后不应发送,实际成功 %d 条", n)
|
||||
}
|
||||
if got := cap.count(); got != 0 {
|
||||
t.Errorf("[场景2] 登出后不应向 MES 发出请求,实际 %d 次", got)
|
||||
}
|
||||
if n, _ := st.PendingQueueCount(); n != 1 {
|
||||
t.Errorf("[场景2] 数据应保留 1 条,实际 %d", n)
|
||||
}
|
||||
|
||||
// 张三重新登录:数据还在,继续发送
|
||||
if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang2")
|
||||
if n := sy.RunOnce(ctx); n != 1 {
|
||||
t.Fatalf("[场景2] 重登后应成功发送 1 条,实际 %d", n)
|
||||
}
|
||||
if got := cap.lastAuth(); got != "Bearer jwt_zhang2" {
|
||||
t.Errorf("[场景2] 应以张三当前有效 JWT 发出,实际 %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景3(换人直接切换 · 各发各的):张三登录录入后未登出,李四直接登录覆盖单行登录态——
|
||||
// 李四会话只发李四自己的新数据;张三的旧数据保留,等张三本人再登录才发。
|
||||
func TestScenario3_DirectUserSwitch(t *testing.T) {
|
||||
st, mc, sy, cap := newTestEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 张三登录 + 录入 1 条(MES 不可达时的离线存量)
|
||||
if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang")
|
||||
if err := st.InsertQueueItem("process_done", `{"sn":"SN-3","operator":"张三"}`, 7, "张三"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 李四直接登录(不登出):单行登录态被覆盖
|
||||
if err := st.SaveStationSession("jwt_li", "li", "李四", 3, time.Now().Add(time.Hour).Unix(), 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_li")
|
||||
// 李四也录入 1 条
|
||||
if err := st.InsertQueueItem("process_done", `{"sn":"SN-3L","operator":"李四"}`, 9, "李四"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 一轮同步:只发李四的 1 条,张三的 1 条保留
|
||||
if n := sy.RunOnce(ctx); n != 1 {
|
||||
t.Fatalf("[场景3] 李四会话应只发送自己的 1 条,实际 %d", n)
|
||||
}
|
||||
if got := cap.lastAuth(); got != "Bearer jwt_li" {
|
||||
t.Errorf("[场景3] 应以李四当前 JWT 发出,实际 %q", got)
|
||||
}
|
||||
items, err := st.PendingQueueItems(10)
|
||||
if err != nil || len(items) != 1 {
|
||||
t.Fatalf("[场景3] 应剩 1 条(张三的),err=%v len=%d", err, len(items))
|
||||
}
|
||||
if items[0].OperatorID != 7 || items[0].OperatorName != "张三" {
|
||||
t.Errorf("[场景3] 剩余应为张三的数据:%+v", items[0])
|
||||
}
|
||||
|
||||
// 张三再登录:发自己的那条
|
||||
if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang2")
|
||||
if n := sy.RunOnce(ctx); n != 1 {
|
||||
t.Fatalf("[场景3] 张三重登后应发送自己的 1 条,实际 %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
// 场景4(拧紧结果同样按操作人隔离):张三的拧紧结果不被李四会话发送,
|
||||
// 张三重登后以当前 JWT 发出。
|
||||
func TestScenario4_TorqueOperatorIsolation(t *testing.T) {
|
||||
st, mc, sy, cap := newTestEnv(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// 张三登录 + 录入拧紧结果(离线存量,operator_id=7)
|
||||
if err := st.SaveStationSession("jwt_zhang", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang")
|
||||
if _, err := st.InsertTorqueResult(store.TorqueResult{
|
||||
WorkOrderNo: "WO-1", Sn: "SN-4", DockCode: "DOCK01", ScrewNo: "S1",
|
||||
Torque: 10, Angle: 90, Result: "OK", Operator: "张三", OperatorID: 7,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 李四登录:不代发
|
||||
if err := st.SaveStationSession("jwt_li", "li", "李四", 3, time.Now().Add(time.Hour).Unix(), 9); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_li")
|
||||
if n := sy.RunOnce(ctx); n != 0 {
|
||||
t.Fatalf("[场景4] 李四不应发送张三的拧紧结果,实际 %d", n)
|
||||
}
|
||||
if n, _ := st.PendingTorqueCount(); n != 1 {
|
||||
t.Errorf("[场景4] 拧紧结果应保留 1 条,实际 %d", n)
|
||||
}
|
||||
|
||||
// 张三重登:发送
|
||||
if err := st.SaveStationSession("jwt_zhang2", "zhang", "张三", 3, time.Now().Add(time.Hour).Unix(), 7); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mc.SetStationToken("jwt_zhang2")
|
||||
if n := sy.RunOnce(ctx); n != 1 {
|
||||
t.Fatalf("[场景4] 张三重登后应发送 1 条拧紧结果,实际 %d", n)
|
||||
}
|
||||
if got := cap.lastAuth(); got != "Bearer jwt_zhang2" {
|
||||
t.Errorf("[场景4] 应以张三当前有效 JWT 发出,实际 %q", got)
|
||||
}
|
||||
if n, _ := st.PendingTorqueCount(); n != 0 {
|
||||
t.Errorf("[场景4] 发送后应无待同步拧紧结果,实际 %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(i int) string {
|
||||
return strconv.Itoa(i)
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package syncer
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -15,17 +16,43 @@ import (
|
||||
const (
|
||||
reportBatchLimit = 200 // 单轮最多处理条数
|
||||
defaultInterval = 15 * time.Second
|
||||
|
||||
// maxQueueRetry / maxTorqueRetry 重试上报上限:超过该次数不再累加 retry_count、不再刷错误日志,
|
||||
// 但仍在每轮继续尝试发送(失败数据留本地等待人工/网络恢复处理,不丢弃、不删除)。
|
||||
maxQueueRetry = 10
|
||||
maxTorqueRetry = 10
|
||||
|
||||
// defaultBacklogWarnThreshold 待上报积压告警默认阈值(建议1:可由 config.Backlog.WarnThreshold 覆盖)。
|
||||
defaultBacklogWarnThreshold = 50
|
||||
|
||||
// localRetentionSec 本地数据保留时长(30 天):超过该时长的离线数据由后台定时清理。
|
||||
localRetentionSec = 30 * 24 * 3600
|
||||
)
|
||||
|
||||
// Syncer 后台同步器:每 15 秒把未同步的 report_queue 与 torque_results 上报 MES。
|
||||
// Syncer 后台同步器:每 15 秒把「当前登录人」未同步的 report_queue 与 torque_results 上报 MES。
|
||||
// 设计原则(2026-10-06 简化):操作工手动点发送 → 用当前登录这人的身份 → 发不出去就是发不出去
|
||||
// (报错、留在本地 SQLite 等人处理),绝不由系统自动决定「等下次有人登录自动补传」。
|
||||
// 数据按 operator_id 隔离:仅当前登录人自己的未同步数据会被发送;其他人录入的数据静默保留,
|
||||
// 不被别人代发,也不对别人可见;同一人重登后可继续发送 / 仅展示失败。
|
||||
type Syncer struct {
|
||||
st *store.Store
|
||||
mes *mes.Client
|
||||
interval time.Duration
|
||||
|
||||
// backlogWarnThreshold 待上报积压告警阈值(建议1):队列+拧紧未同步合计超过该值打 WARN;
|
||||
// 可由 SetBacklogThreshold 从配置注入,<=0 回退默认 50。
|
||||
backlogWarnThreshold int
|
||||
}
|
||||
|
||||
// SetBacklogThreshold 从配置注入积压告警阈值(建议1);n<=0 不改(保留默认 50)。
|
||||
func (s *Syncer) SetBacklogThreshold(n int) {
|
||||
if n > 0 {
|
||||
s.backlogWarnThreshold = n
|
||||
}
|
||||
}
|
||||
|
||||
func New(st *store.Store, mc *mes.Client) *Syncer {
|
||||
return &Syncer{st: st, mes: mc, interval: defaultInterval}
|
||||
return &Syncer{st: st, mes: mc, interval: defaultInterval, backlogWarnThreshold: defaultBacklogWarnThreshold}
|
||||
}
|
||||
|
||||
// Run 周期冲刷循环,随 ctx 取消退出。
|
||||
@@ -33,6 +60,8 @@ func (s *Syncer) Run(ctx context.Context) {
|
||||
logx.Infof("后台同步协程已启动:每 %s 冲刷一次未上报数据", s.interval)
|
||||
ticker := time.NewTicker(s.interval)
|
||||
defer ticker.Stop()
|
||||
cleanTicker := time.NewTicker(time.Hour)
|
||||
defer cleanTicker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -42,6 +71,12 @@ func (s *Syncer) Run(ctx context.Context) {
|
||||
if n := s.RunOnce(ctx); n > 0 {
|
||||
logx.Infof("本轮同步成功 %d 条", n)
|
||||
}
|
||||
case <-cleanTicker.C:
|
||||
if deleted, err := s.st.CleanupOld(localRetentionSec); err != nil {
|
||||
logx.Errorf("清理本地过期数据失败: %v", err)
|
||||
} else if deleted > 0 {
|
||||
logx.Infof("已清理本地 %d 条超过 30 天的离线数据", deleted)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,13 +85,50 @@ func (s *Syncer) Run(ctx context.Context) {
|
||||
func (s *Syncer) RunOnce(ctx context.Context) int {
|
||||
n := s.flushQueue(ctx)
|
||||
n += s.flushTorque(ctx)
|
||||
// 积压监控(建议1):待上报总量超阈值打 WARN,供日志采集/告警。
|
||||
// 区分两类积压,输出固定可匹配的日志标记(BACKLOG_ALERT_IDENTITY / BACKLOG_ALERT_NETWORK):
|
||||
// - IDENTITY:当前未登录 → 数据等待当前操作人登录后继续发送(可恢复,不阻断产线);
|
||||
// - NETWORK:已登录仍堆积 → 疑似 MES 网络/业务拒绝,需排查 MES 连通性与返回。
|
||||
if qc, err := s.st.PendingQueueCount(); err == nil {
|
||||
if tc, err2 := s.st.PendingTorqueCount(); err2 == nil {
|
||||
if total := qc + tc; total > int64(s.backlogWarnThreshold) {
|
||||
hasSession := false
|
||||
if ss, e := s.st.GetStationSession(); e == nil && ss != nil && ss.Token != "" {
|
||||
if ss.ExpireAt <= 0 || time.Now().Unix() < ss.ExpireAt {
|
||||
hasSession = true
|
||||
}
|
||||
}
|
||||
if hasSession {
|
||||
logx.Errorf("BACKLOG_ALERT_NETWORK 离线队列积压 %d 条(队列 %d / 拧紧 %d):存在有效登录态仍堆积,疑似 MES 网络或业务拒绝,请检查 MES 连通性与业务返回", total, qc, tc)
|
||||
} else {
|
||||
logx.Errorf("BACKLOG_ALERT_IDENTITY 离线队列积压 %d 条(队列 %d / 拧紧 %d):当前未登录,等待当前操作人登录后继续发送", total, qc, tc)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// flushTorque 上报未同步拧紧结果:
|
||||
// POST /api/internal/torque/report;成功标记 synced=1,失败保持 0 等待下轮重试。
|
||||
// currentSession 取当前有效的在岗登录态;无登录态或凭证已过期返回 nil。
|
||||
func (s *Syncer) currentSession() *store.StationSession {
|
||||
ss, err := s.st.GetStationSession()
|
||||
if err != nil || ss == nil || ss.Token == "" {
|
||||
return nil
|
||||
}
|
||||
if ss.ExpireAt > 0 && time.Now().Unix() >= ss.ExpireAt {
|
||||
return nil
|
||||
}
|
||||
return ss
|
||||
}
|
||||
|
||||
// flushTorque 上报「当前登录人」未同步拧紧结果:POST /api/internal/torque/report;
|
||||
// 成功标记 synced=1,失败保持 0 等待下轮重试(同一登录人重登后续发)。
|
||||
func (s *Syncer) flushTorque(ctx context.Context) int {
|
||||
rows, err := s.st.ListTorqueResults("", true, reportBatchLimit)
|
||||
ss := s.currentSession()
|
||||
if ss == nil {
|
||||
return 0
|
||||
}
|
||||
rows, err := s.st.PendingTorqueResultsForOperator(ss.UserID, reportBatchLimit)
|
||||
if err != nil {
|
||||
logx.Errorf("查询未同步拧紧结果失败: %v", err)
|
||||
return 0
|
||||
@@ -88,8 +160,16 @@ func (s *Syncer) flushTorque(ctx context.Context) int {
|
||||
"result": t.Result,
|
||||
"operator": t.Operator,
|
||||
}
|
||||
// 用当前登录态(即当前在岗操作人)的身份发送,失败即留本地。
|
||||
if _, _, err := s.mes.Post("/api/internal/torque/report", body); err != nil {
|
||||
logx.Errorf("上报拧紧结果失败(id=%d sn=%s): %v", t.ID, t.Sn, err)
|
||||
if errors.Is(err, mes.ErrAuth) {
|
||||
// 当前登录态失效(理论上 currentSession 已拦截):跳过,等待重新登录后续传。
|
||||
continue
|
||||
}
|
||||
logx.Errorf("上报拧紧结果失败(id=%d sn=%s 第 %d 次): %v", t.ID, t.Sn, t.RetryCount+1, err)
|
||||
if t.RetryCount+1 < maxTorqueRetry {
|
||||
_ = s.st.BumpTorqueRetry(t.ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
done = append(done, t.ID)
|
||||
@@ -103,15 +183,20 @@ func (s *Syncer) flushTorque(ctx context.Context) int {
|
||||
return count
|
||||
}
|
||||
|
||||
// flushQueue 上报未同步的离线缓存队列,payload 原样透传:
|
||||
// flushQueue 上报「当前登录人」未同步的离线缓存队列,payload 原样透传:
|
||||
// - kind=process_done → POST /api/internal/station/report
|
||||
// - kind=temp_store → POST /api/internal/station/checkin
|
||||
// - kind=online_register → POST /api/internal/workpiece/online(上线建档)
|
||||
// - kind=offline_finish → POST /api/internal/workpiece/done(下线完工入库)
|
||||
//
|
||||
// 成功标记 synced=1;失败 synced 保持 0 并累计 retry_count。
|
||||
// 每条使用当前在岗登录态 JWT 发送;成功标记 synced=1;失败 synced 保持 0 并累计 retry_count,
|
||||
// 留本地等待同一操作人重新登录后续传或人工排查。仅发送「当前登录人自己」的数据,他人数据不被代发。
|
||||
func (s *Syncer) flushQueue(ctx context.Context) int {
|
||||
items, err := s.st.PendingQueueItems(reportBatchLimit)
|
||||
ss := s.currentSession()
|
||||
if ss == nil {
|
||||
return 0
|
||||
}
|
||||
items, err := s.st.PendingQueueItemsForOperator(ss.UserID, reportBatchLimit)
|
||||
if err != nil {
|
||||
logx.Errorf("查询待上报队列失败: %v", err)
|
||||
return 0
|
||||
@@ -142,8 +227,13 @@ func (s *Syncer) flushQueue(ctx context.Context) int {
|
||||
}
|
||||
|
||||
if _, _, err := s.mes.Post(path, json.RawMessage(it.Payload)); err != nil {
|
||||
if errors.Is(err, mes.ErrAuth) {
|
||||
continue
|
||||
}
|
||||
logx.Errorf("上报队列失败(kind=%s id=%d 第 %d 次): %v", it.Kind, it.ID, it.RetryCount+1, err)
|
||||
_ = s.st.BumpQueueRetry(it.ID)
|
||||
if it.RetryCount+1 < maxQueueRetry {
|
||||
_ = s.st.BumpQueueRetry(it.ID)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := s.st.MarkQueueSynced(it.ID); err != nil {
|
||||
@@ -153,4 +243,4 @@ func (s *Syncer) flushQueue(ctx context.Context) int {
|
||||
count++
|
||||
}
|
||||
return count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package syncer_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"bj_power_workstation/internal/mes"
|
||||
"bj_power_workstation/internal/store"
|
||||
"bj_power_workstation/internal/syncer"
|
||||
)
|
||||
|
||||
// TestStationAuthStaleNoDataLoss 运行期验证核实3:工位登录态过期(JWT 401)时,
|
||||
// 离线 syncer 暂停发送、数据保留在本地 SQLite;同一操作人重新登录(有效凭证)后继续发送,数据不丢。
|
||||
func TestStationAuthStaleNoDataLoss(t *testing.T) {
|
||||
// 假 MES:Bearer=valid 返回 200,其余返回 401
|
||||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") == "Bearer valid" {
|
||||
w.WriteHeader(200)
|
||||
_, _ = w.Write([]byte(`{"code":0}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(401)
|
||||
_, _ = w.Write([]byte(`{"code":401,"message":"unauthorized"}`))
|
||||
}))
|
||||
defer ts.Close()
|
||||
|
||||
dbPath := t.TempDir() + "/ws.db"
|
||||
st, err := store.Open(dbPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer st.Close()
|
||||
|
||||
// 注入一条未同步拧紧结果(模拟离线缓存)
|
||||
if _, err := st.InsertTorqueResult(store.TorqueResult{
|
||||
WorkOrderNo: "WO-1", Sn: "SN-1", DockCode: "DOCK01", ScrewNo: "S1",
|
||||
Torque: 10, Angle: 90, Result: "OK", Operator: "张三",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
mc := mes.New(ts.URL, "tok")
|
||||
mc.SetStationToken("expired") // 当前 client token(镜像真实登录)
|
||||
_ = st.SaveStationSession("expired", "u", "U", 1, time.Now().Add(-time.Hour).Unix(), 0) // 登录态已过期
|
||||
|
||||
sy := syncer.New(st, mc)
|
||||
ctx := context.Background()
|
||||
|
||||
// 阶段A:过期凭证 → 401,syncer 整轮暂停,数据保留在本地
|
||||
n := sy.RunOnce(ctx)
|
||||
if n != 0 {
|
||||
t.Errorf("[核实3] 过期凭证下应暂停发送返回 0,实际 %d", n)
|
||||
}
|
||||
pending, _ := st.PendingTorqueCount()
|
||||
if pending != 1 {
|
||||
t.Errorf("[核实3] 数据应保留 1 条,实际 %d", pending)
|
||||
}
|
||||
list, _ := st.ListTorqueResults("", true, 10)
|
||||
if len(list) == 1 && list[0].RetryCount != 0 {
|
||||
t.Errorf("[核实3] 过期凭证不应 bump 重试次数,实际 %d", list[0].RetryCount)
|
||||
}
|
||||
if len(list) == 1 && list[0].Synced {
|
||||
t.Errorf("[核实3] 过期凭证不应标记已同步")
|
||||
}
|
||||
t.Logf("[核实3 过期凭证] RunOnce=%d pending=%d retry=%d(数据保留在本地)", n, pending, list[0].RetryCount)
|
||||
|
||||
// 阶段B:重新登录(有效凭证)→ syncer 恢复,数据成功上报
|
||||
mc.SetStationToken("valid") // 当前 client token
|
||||
_ = st.SaveStationSession("valid", "u", "U", 1, time.Now().Add(time.Hour).Unix(), 0) // 登录态恢复有效
|
||||
|
||||
n = sy.RunOnce(ctx)
|
||||
if n != 1 {
|
||||
t.Errorf("[核实3] 重新登录后应成功发送 1 条,实际 %d", n)
|
||||
}
|
||||
pending, _ = st.PendingTorqueCount()
|
||||
if pending != 0 {
|
||||
t.Errorf("[核实3] 上报后应无待同步数据,实际 %d", pending)
|
||||
}
|
||||
t.Logf("[核实3 重新登录] RunOnce=%d pending=%d(发送成功,数据不丢)", n, pending)
|
||||
}
|
||||
Reference in New Issue
Block a user