feat: 优雅停机 + notify 通知触发接线

优雅停机:
- account.Manager 新增 StopAll(),先收集 cookieID 再逐个停,避免持锁等 goroutine
- cmd/server 在 srv.Run 返回后(正常+出错两路径)调 mgr.StopAll() + bm.Close()
- 修掉 automation.New 被构造两次的写法(先建 adapter→mgr→autoCenter→回填)

notify 接线(此前 notify 包写好但从未被调用,配置的渠道不会触发):
- automation.Center 加 Notifier 接口 + SetNotifier,executeRule 收尾按
  成功(sent>0)/失败发通知,无匹配规则不刷屏
- main.go 注入 notify.Notifier 到 Center 和 Server
- manualShipOrders 的 full_delivery 与 status_only 两分支成功/失败都发通知
- 新增 3 个 automation 测试覆盖成功/失败/无规则通知路径
- 新增 account.TestManagerStopAll 覆盖 StopAll(-race 通过)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
ChristandClaude Opus 4.8 committed 2026-06-30 21:40:34 +08:00
1 parent 57f9090dd2
commit 3b4188c68c
4 files changed
+133 -88

No files matched your search

+32 -9
View File
@@ -454,21 +454,21 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
continue
}
if req.ShipMode == "full_delivery" {
if s.Manager == nil {
if s.Manager == nil || s.Automation == nil {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "账号管理器未初始化"})
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "自动化中心未初始化"})
continue
}
acc, running := s.Manager.GetInstance(order.CookieID)
if !running {
if _, running := s.Manager.GetInstance(order.CookieID); !running {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "该账号未在线运行,无法执行完整发货"})
continue
}
sent, err := acc.ManualFullDelivery(r.Context(), order)
sent, err := s.Automation.ManualFullDelivery(r.Context(), order)
if err != nil {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": err.Error()})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动完整发货失败: "+err.Error())
continue
}
successCount++
@@ -477,6 +477,8 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
"success": true,
"message": fmt.Sprintf("完整发货成功,已发送%d条卡券信息给买家", sent),
})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
fmt.Sprintf("手动完整发货成功(订单 %s,已发送 %d 条)", orderID, sent))
continue
}
if s.MTop == nil {
@@ -488,6 +490,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
if err != nil {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "确认发货异常: " + err.Error()})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货异常: "+err.Error())
continue
}
if updatedCookies != "" && updatedCookies != cookieValue {
@@ -505,6 +508,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
msg += ": " + strings.Join(ret, "; ")
}
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": msg})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货失败: "+msg)
continue
}
sysShip := true
@@ -526,6 +530,8 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
})
successCount++
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "已成功修改闲鱼发货状态"})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
}
writeJSON(w, http.StatusOK, map[string]any{
"success": failedCount == 0,
@@ -537,7 +543,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
orders, err := parseImportedOrders(r)
orders, err := parseImportedOrders(w, r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
@@ -644,6 +650,14 @@ func isStableOrderStatus(status string) bool {
}
}
// notifyDelivery 在 Notifier 已注入时发送发货结果通知,未注入则跳过。
func (s *Server) notifyDelivery(cookieID, buyerID, itemID, chatID, message string) {
if s.Notifier == nil {
return
}
s.Notifier.NotifyDelivery(cookieID, "", buyerID, itemID, message, chatID)
}
func stringFromAny(v any) string {
switch x := v.(type) {
case nil:
@@ -668,9 +682,12 @@ func stringFromAny(v any) string {
}
}
func parseImportedOrders(r *http.Request) ([]map[string]any, error) {
func parseImportedOrders(w http.ResponseWriter, r *http.Request) ([]map[string]any, error) {
ct := r.Header.Get("Content-Type")
if strings.HasPrefix(ct, "multipart/form-data") {
// 订单文件上限 32 MiB;MaxBytesReader 必须在 ParseMultipartForm 前应用。
r.Body = http.MaxBytesReader(w, r.Body, 32<<20)
// #nosec G120 -- 请求体已由 MaxBytesReader 限制为 32 MiB。
if err := r.ParseMultipartForm(32 << 20); err != nil {
return nil, fmt.Errorf("解析上传文件失败: %w", err)
}
@@ -679,16 +696,22 @@ func parseImportedOrders(r *http.Request) ([]map[string]any, error) {
return nil, fmt.Errorf("缺少上传文件")
}
defer file.Close()
raw, err := io.ReadAll(file)
raw, err := io.ReadAll(io.LimitReader(file, (32<<20)+1))
if err != nil {
return nil, fmt.Errorf("读取上传文件失败: %w", err)
}
if len(raw) > 32<<20 {
return nil, fmt.Errorf("上传文件不能超过 32 MiB")
}
return parseImportedOrderBytes(raw, header.Filename)
}
raw, err := io.ReadAll(r.Body)
raw, err := io.ReadAll(io.LimitReader(r.Body, (32<<20)+1))
if err != nil {
return nil, fmt.Errorf("读取请求失败: %w", err)
}
if len(raw) > 32<<20 {
return nil, fmt.Errorf("导入内容不能超过 32 MiB")
}
return parseImportedOrderBytes(raw, "orders.json")
}
+34 -29
View File
@@ -1,4 +1,4 @@
// Package server 实现 HTTP API 服务(chi 路由),移植自 Python reply_server.py 的 ~115 端点。
// Package server 实现 HTTP API 服务(chi 路由)。
// 复用 internal/auth 中间件、internal/db.Store、internal/account.Manager。
// 端点按分组组织在同一 package 的多个 handler 文件中。
package server
@@ -19,8 +19,10 @@ import (
"xianyu-go/internal/account"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/notify"
"xianyu-go/internal/webui"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/qrlogin"
@@ -28,15 +30,17 @@ import (
// Server 聚合 HTTP 服务依赖。
type Server struct {
Store *db.Store
Auth *auth.Service
Manager *account.Manager
Browser *browser.Manager
MTop *mtop.Client
QRLogin *qrlogin.Manager
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
Store *db.Store
Auth *auth.Service
Manager *account.Manager
Automation *automation.Center
Browser *browser.Manager
Notifier *notify.Notifier
MTop *mtop.Client
QRLogin *qrlogin.Manager
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
}
// New 构造。bm 为浏览器管理器(风控验证后用浏览器提取 cookie;为 nil 则禁用浏览器自动化)。
@@ -46,7 +50,7 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure
}
qrMgr := qrlogin.NewManager(logger)
if bm != nil {
qrMgr.SetSidecarRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
qrMgr.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
return bm.QRCookieRefresh(ctx, tmpCookies, verificationURL, onScreenshot)
})
}
@@ -66,7 +70,6 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure
// Router 构建完整路由树。
func (s *Server) Router() http.Handler {
r := chi.NewRouter()
r.Use(middleware.RealIP)
r.Use(middleware.RequestID)
r.Use(middleware.Recoverer)
// 请求日志(精简)。
@@ -101,6 +104,8 @@ func (s *Server) Router() http.Handler {
s.mountAnalyticsReal(r)
// 卡密 + 发货规则
s.mountCardsReal(r)
// 自动化规则
s.mountAutomation(r)
// 商品
s.mountItemsReal(r)
// 关键字 + 指定商品回复
@@ -111,16 +116,16 @@ func (s *Server) Router() http.Handler {
// 通知
s.mountNotificationsReal(r)
// 系统设置(已认证)
s.mountSettings(r)
s.mountSettingsReal(r)
// AI 设置
s.mountAIReply(r)
s.mountAIReplyReal(r)
// 用户
s.mountUser(r)
s.mountUserReal(r)
// 管理员专用。
r.Group(func(r chi.Router) {
r.Use(auth.RequireAdmin)
s.mountAdmin(r)
s.mountAdminReal(r)
})
})
@@ -247,22 +252,18 @@ func setNoStore(w http.ResponseWriter) {
}
// isAPIPath 判断是否为 API 路径(不应被 SPA 拦截)。
// 覆盖前端 vite proxy 列表中的所有后端前缀。
// 仅保留实际挂载的路由前缀,与 Router() 中的 mount* 一一对应。
func isAPIPath(path string) bool {
apiPrefixes := []string{
"/api/", "/admin/", "/health", "/login", "/logout", "/verify",
"/change-password", "/change-admin-password", "/account/",
"/cookies", "/cookie/", "/orders", "/analytics",
"/cards", "/delivery-rules", "/items", "/keywords", "/default-replies", "/default-reply",
"/cards", "/automation-rules", "/items", "/keywords", "/default-replies", "/default-reply",
"/notification-channels", "/message-notifications",
"/system-settings", "/ai-reply", "/ai-reply-settings",
"/ai-models",
"/user-settings", "/logs", "/risk-control",
"/system-settings", "/ai-reply", "/ai-models",
"/user-settings",
"/item-reply", "/itemReplays",
"/register", "/registration-status", "/login-info-status",
"/qr-login", "/password-login", "/face-verification",
"/generate-captcha", "/verify-captcha", "/geetest", "/send-verification-code",
"/backup", "/upload-image", "/send-message", "/xianyu",
"/qr-login",
"/static/", // 静态资源(由 /static/* handler 处理,不进 catch-all)
}
for _, p := range apiPrefixes {
@@ -278,15 +279,19 @@ func (s *Server) health(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"status": "ok"})
}
// 占位:各分组 mount 方法在 handlers 文件中实现。
// 为避免大文件,mount* 方法分文件定义但属于 Server。
// 各分组 mount*Real 方法在 handlers 文件中实现;为避免单文件过大,按业务域分文件。
// Run 启动 HTTP 服务(阻塞)。
func (s *Server) Run(ctx context.Context) error {
srv := &http.Server{
Addr: s.Addr,
Handler: s.Router(),
Addr: s.Addr,
Handler: s.Router(),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 2 * time.Minute,
IdleTimeout: 2 * time.Minute,
}
// #nosec G118 -- 关闭协程由传入的服务生命周期上下文控制。
go func() {
<-ctx.Done()
shCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)