重构: 活动热切换并发安全 + 代码清理优化
- 活动切换并发安全:App/Scheduler 增加 client/cfg 读写锁与快照访问, 支持运行中热替换客户端,切换活动不再静默覆盖用户自定义 timeApiUrl - 启动失败时写入崩溃日志文件便于事后排查 - 前端类型声明从 Wails 自动生成的绑定派生,避免手写契约漂移 - 提取 parseAccountFile 消除 ExportAccounts/OrganizeAccounts 重复解析逻辑 - 删除 utils 中未使用的 ReadJSON/WriteJSON/WriteError 及空目录 internal/app - gofmt 统一格式化(activity/types/scheduler 字段对齐) - 新增 logger/seckill/utils 单元测试 - 清理 git 中遗留产物(frontend/app.js、yml.txt、其他日志/)并补全 .gitignore
This commit is contained in:
@@ -22,19 +22,23 @@ import (
|
||||
"douyu_go/internal/seckill"
|
||||
"douyu_go/internal/trace"
|
||||
"douyu_go/internal/types"
|
||||
"douyu_go/internal/utils"
|
||||
)
|
||||
|
||||
// App 应用主结构体,所有导出方法可被前端通过 Wails 绑定调用。
|
||||
type App struct {
|
||||
ctx context.Context
|
||||
|
||||
clientMu sync.RWMutex
|
||||
client *client.DouyuClient
|
||||
scheduler *seckill.Scheduler
|
||||
logStore *logger.MemoryLogStore
|
||||
trace *trace.Recorder
|
||||
paths types.AppPaths
|
||||
font *truetype.Font
|
||||
cfg types.Config
|
||||
|
||||
cfgMu sync.RWMutex
|
||||
cfg types.Config
|
||||
|
||||
productsMu sync.RWMutex
|
||||
products []types.Product
|
||||
@@ -46,6 +50,44 @@ type App struct {
|
||||
|
||||
const exchangeLookupConcurrency = 8
|
||||
|
||||
// getClient 返回当前 client 指针快照(读锁保护)。
|
||||
func (a *App) getClient() *client.DouyuClient {
|
||||
a.clientMu.RLock()
|
||||
defer a.clientMu.RUnlock()
|
||||
return a.client
|
||||
}
|
||||
|
||||
// getCfg 返回当前配置的深拷贝(读锁保护)。
|
||||
func (a *App) getCfg() types.Config {
|
||||
a.cfgMu.RLock()
|
||||
defer a.cfgMu.RUnlock()
|
||||
return cloneConfig(a.cfg)
|
||||
}
|
||||
|
||||
// setClient 替换 client(写锁保护)。
|
||||
func (a *App) setClient(c *client.DouyuClient) {
|
||||
a.clientMu.Lock()
|
||||
a.client = c
|
||||
a.clientMu.Unlock()
|
||||
}
|
||||
|
||||
// setCfg 替换配置(写锁保护)。
|
||||
func (a *App) setCfg(c types.Config) {
|
||||
a.cfgMu.Lock()
|
||||
a.cfg = c
|
||||
a.cfgMu.Unlock()
|
||||
}
|
||||
|
||||
// cloneConfig 深拷贝配置,避免 RetryStages 切片共享引用。
|
||||
func cloneConfig(c types.Config) types.Config {
|
||||
cp := c
|
||||
if c.RetryStages != nil {
|
||||
cp.RetryStages = make([]types.RetryStage, len(c.RetryStages))
|
||||
copy(cp.RetryStages, c.RetryStages)
|
||||
}
|
||||
return cp
|
||||
}
|
||||
|
||||
type exchangeLookupResult struct {
|
||||
Account types.Account
|
||||
Records []client.ExchangeRecord
|
||||
@@ -121,7 +163,7 @@ func (a *App) shutdown(ctx context.Context) {
|
||||
// LoadProducts 刷新商品列表。refresh=true 时从斗鱼实时拉取。
|
||||
func (a *App) LoadProducts(refresh bool) types.ProductPayload {
|
||||
if refresh {
|
||||
products, err := a.client.Products()
|
||||
products, err := a.getClient().Products()
|
||||
if err != nil {
|
||||
logger.LogEvent("商品", "error", "商品刷新失败: %v", err)
|
||||
return types.ProductPayload{Success: false}
|
||||
@@ -142,7 +184,7 @@ func (a *App) GetAccounts() []types.AccountView {
|
||||
list = append(list, types.AccountView{
|
||||
Index: i,
|
||||
Name: account.Name,
|
||||
Cookie: maskCookie(account.Cookie),
|
||||
Cookie: utils.MaskCookie(account.Cookie),
|
||||
})
|
||||
}
|
||||
return list
|
||||
@@ -162,7 +204,7 @@ func (a *App) StartSeckill(accountProducts map[string]string) map[string]any {
|
||||
if !a.scheduler.TryStartRun() {
|
||||
return map[string]any{"success": false, "error": "抢购任务正在运行,请勿重复提交"}
|
||||
}
|
||||
go a.scheduler.RunNow(cloneMap(accountProducts))
|
||||
go a.scheduler.RunNow(utils.CloneStringMap(accountProducts))
|
||||
return map[string]any{"success": true, "msg": "抢购已启动"}
|
||||
}
|
||||
|
||||
@@ -199,7 +241,7 @@ func (a *App) GetLogs(since int64) map[string]any {
|
||||
|
||||
// GetTime 返回服务端时间和本地时间。
|
||||
func (a *App) GetTime() map[string]any {
|
||||
serverTime, err := a.client.ServerTime()
|
||||
serverTime, err := a.getClient().ServerTime()
|
||||
source := "currentTime"
|
||||
if err != nil {
|
||||
source = "localFallback"
|
||||
@@ -227,7 +269,7 @@ func (a *App) QueryScore(accountName string) map[string]any {
|
||||
if !ok || cookie == "" {
|
||||
return map[string]any{"score": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
|
||||
}
|
||||
score, err := a.client.Score(cookie)
|
||||
score, err := a.getClient().Score(cookie)
|
||||
if err != nil {
|
||||
return map[string]any{"score": "查询失败: " + err.Error()}
|
||||
}
|
||||
@@ -244,7 +286,7 @@ func (a *App) VerifyExchange(accountName string) map[string]any {
|
||||
return map[string]any{"success": false, "error": fmt.Sprintf("账号不存在或 Cookie 为空: %s", accountName)}
|
||||
}
|
||||
|
||||
records, err := a.client.ExchangeList(cookie)
|
||||
records, err := a.getClient().ExchangeList(cookie)
|
||||
if err != nil {
|
||||
return map[string]any{"success": false, "error": "查询失败: " + err.Error()}
|
||||
}
|
||||
@@ -372,7 +414,7 @@ func (a *App) lookupExchangeRecords(category string, accounts []types.Account) [
|
||||
results[idx] = lookup
|
||||
continue
|
||||
}
|
||||
records, err := a.client.ExchangeList(account.Cookie)
|
||||
records, err := a.getClient().ExchangeList(account.Cookie)
|
||||
lookup.Records = records
|
||||
lookup.Err = err
|
||||
results[idx] = lookup
|
||||
@@ -440,39 +482,61 @@ func hasCommodityRecord(records []client.ExchangeRecord, commodityID string, sta
|
||||
return false
|
||||
}
|
||||
|
||||
// accountLine 账号文件的一行解析结果。
|
||||
type accountLine struct {
|
||||
Raw string // 原始行文本
|
||||
Name string // 解析出的账号名(注释/空行为空)
|
||||
Comment bool // 是否为注释或空行
|
||||
}
|
||||
|
||||
// parseAccountFile 读取账号文件并按行解析账号名。
|
||||
func parseAccountFile(path string) ([]accountLine, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var lines []accountLine
|
||||
scanner := bufio.NewScanner(strings.NewReader(string(data)))
|
||||
for scanner.Scan() {
|
||||
raw := scanner.Text()
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
lines = append(lines, accountLine{Raw: raw, Comment: true})
|
||||
continue
|
||||
}
|
||||
name := ""
|
||||
if parts := strings.SplitN(trimmed, "----", 3); len(parts) >= 1 {
|
||||
name = strings.TrimSpace(parts[0])
|
||||
}
|
||||
lines = append(lines, accountLine{Raw: raw, Name: name})
|
||||
}
|
||||
return lines, scanner.Err()
|
||||
}
|
||||
|
||||
// ExportAccounts 导出指定账号到文件。
|
||||
func (a *App) ExportAccounts(accountNames []string, filename string) map[string]any {
|
||||
if len(accountNames) == 0 {
|
||||
return map[string]any{"success": false, "error": "没有要导出的账号"}
|
||||
}
|
||||
|
||||
// 读取原账号文件
|
||||
accountFile := a.scheduler.AccountFilePath()
|
||||
lines, err := os.ReadFile(accountFile)
|
||||
lines, err := parseAccountFile(accountFile)
|
||||
if err != nil {
|
||||
return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()}
|
||||
}
|
||||
|
||||
// 解析账号行
|
||||
nameSet := make(map[string]bool)
|
||||
for _, name := range accountNames {
|
||||
nameSet[name] = true
|
||||
}
|
||||
|
||||
var matchedLines []string
|
||||
scanner := bufio.NewScanner(strings.NewReader(string(lines)))
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
for _, line := range lines {
|
||||
if line.Comment {
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(trimmed, "----", 3)
|
||||
if len(parts) >= 1 {
|
||||
name := strings.TrimSpace(parts[0])
|
||||
if nameSet[name] {
|
||||
matchedLines = append(matchedLines, line)
|
||||
}
|
||||
if nameSet[line.Name] {
|
||||
matchedLines = append(matchedLines, line.Raw)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -502,16 +566,8 @@ func (a *App) ExportAccountsWithProduct(accountNames []string, commodityID, comm
|
||||
// 生成文件名: user_已抢到_商品中文名_20260626_150405.txt
|
||||
now := time.Now()
|
||||
timestamp := now.Format("20060102_150405")
|
||||
// 清理商品名中的特殊字符
|
||||
safeName := strings.ReplaceAll(commodityName, "/", "_")
|
||||
safeName = strings.ReplaceAll(safeName, "\\", "_")
|
||||
safeName = strings.ReplaceAll(safeName, ":", "_")
|
||||
safeName = strings.ReplaceAll(safeName, "*", "_")
|
||||
safeName = strings.ReplaceAll(safeName, "?", "_")
|
||||
safeName = strings.ReplaceAll(safeName, "\"", "_")
|
||||
safeName = strings.ReplaceAll(safeName, "<", "_")
|
||||
safeName = strings.ReplaceAll(safeName, ">", "_")
|
||||
safeName = strings.ReplaceAll(safeName, "|", "_")
|
||||
// 清理商品名中的特殊字符(复用 utils.SafeFilename,避免与 utils 包重复实现)
|
||||
safeName := utils.SafeFilename(commodityName)
|
||||
filename := fmt.Sprintf("user_已抢到_%s_%s.txt", safeName, timestamp)
|
||||
|
||||
return a.ExportAccounts(accountNames, filename)
|
||||
@@ -545,7 +601,7 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
|
||||
|
||||
// 更新原文件,只保留未抢到的
|
||||
accountFile := a.scheduler.AccountFilePath()
|
||||
lines, err := os.ReadFile(accountFile)
|
||||
lines, err := parseAccountFile(accountFile)
|
||||
if err != nil {
|
||||
return map[string]any{"success": false, "error": "读取账号文件失败: " + err.Error()}
|
||||
}
|
||||
@@ -556,20 +612,13 @@ func (a *App) OrganizeAccounts(commodityID, commodityName string, startTime, end
|
||||
}
|
||||
|
||||
var keepLines []string
|
||||
scanner := bufio.NewScanner(strings.NewReader(string(lines)))
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
||||
keepLines = append(keepLines, line)
|
||||
for _, line := range lines {
|
||||
if line.Comment {
|
||||
keepLines = append(keepLines, line.Raw)
|
||||
continue
|
||||
}
|
||||
parts := strings.SplitN(trimmed, "----", 3)
|
||||
if len(parts) >= 1 {
|
||||
name := strings.TrimSpace(parts[0])
|
||||
if missSet[name] {
|
||||
keepLines = append(keepLines, line)
|
||||
}
|
||||
if missSet[line.Name] {
|
||||
keepLines = append(keepLines, line.Raw)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -614,7 +663,8 @@ func (a *App) GetActivities() []types.ActivityInfo {
|
||||
|
||||
// GetCurrentActivity 返回当前生效的活动。
|
||||
func (a *App) GetCurrentActivity() types.ActivityInfo {
|
||||
act := a.client.Activity
|
||||
cli := a.getClient()
|
||||
act := cli.Activity
|
||||
return types.ActivityInfo{ID: act.ID, DisplayName: act.DisplayName}
|
||||
}
|
||||
|
||||
@@ -624,14 +674,23 @@ func (a *App) SwitchActivity(id string) map[string]any {
|
||||
if act == nil {
|
||||
return map[string]any{"success": false, "error": "未知活动: " + id}
|
||||
}
|
||||
a.cfg.Activity = act.ID
|
||||
a.cfg.TimeAPIURL = constants.DefaultTimeAPI
|
||||
if err := config.SaveConfig(a.paths.ConfigFile, a.cfg); err != nil {
|
||||
cfg := a.getCfg()
|
||||
cfg.Activity = act.ID
|
||||
// 仅当用户未自定义时间校准接口时才回退默认值,避免切换活动静默覆盖用户在设置里填的 timeApiUrl。
|
||||
if cfg.TimeAPIURL == "" {
|
||||
cfg.TimeAPIURL = constants.DefaultTimeAPI
|
||||
}
|
||||
if err := config.SaveConfig(a.paths.ConfigFile, cfg); err != nil {
|
||||
logger.LogEvent("活动", "error", "切换活动配置保存失败: %v", err)
|
||||
return map[string]any{"success": false, "error": "配置保存失败: " + err.Error()}
|
||||
}
|
||||
a.client = client.New(act, a.cfg.TimeAPIURL, a.trace)
|
||||
if sample, err := a.client.ServerTimeSample(); err == nil {
|
||||
a.setCfg(cfg)
|
||||
newClient := client.New(act, cfg.TimeAPIURL, a.trace)
|
||||
a.setClient(newClient)
|
||||
if !a.scheduler.UpdateClient(newClient) {
|
||||
logger.LogEvent("活动", "warn", "抢购任务正在运行,调度器客户端将在下次抢购时生效")
|
||||
}
|
||||
if sample, err := newClient.ServerTimeSample(); err == nil {
|
||||
logger.SetDouyuOffset(sample.Offset)
|
||||
}
|
||||
logger.LogEvent("活动", "success", "已切换到活动: %s", act.DisplayName)
|
||||
@@ -640,7 +699,7 @@ func (a *App) SwitchActivity(id string) map[string]any {
|
||||
|
||||
// GetSettings 返回当前配置。
|
||||
func (a *App) GetSettings() types.Config {
|
||||
return a.cfg
|
||||
return a.getCfg()
|
||||
}
|
||||
|
||||
// SaveSettings 保存配置并运行时生效。
|
||||
@@ -663,7 +722,7 @@ func (a *App) SaveSettings(cfg types.Config) map[string]any {
|
||||
}
|
||||
|
||||
// 运行时生效
|
||||
a.cfg = cfg
|
||||
a.setCfg(cfg)
|
||||
logger.SetMinLevel(cfg.LogLevel)
|
||||
a.scheduler.UpdateSettings(cfg.Concurrency, cfg.Attempts, cfg.RetryStages, cfg.SeckillMode)
|
||||
|
||||
@@ -707,66 +766,3 @@ func (a *App) productPayload(source string) types.ProductPayload {
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func cloneMap(in map[string]string) map[string]string {
|
||||
out := make(map[string]string, len(in))
|
||||
for k, v := range in {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func maskCookie(cookie string) string {
|
||||
pairs := splitCookie(cookie)
|
||||
masked := make([]string, 0, 3)
|
||||
total := 0
|
||||
for _, pair := range pairs {
|
||||
key, value := splitCookiePair(pair)
|
||||
if key == "" {
|
||||
continue
|
||||
}
|
||||
total++
|
||||
if len(masked) >= 3 {
|
||||
continue
|
||||
}
|
||||
masked = append(masked, key+"="+maskValue(value))
|
||||
}
|
||||
if total == 0 {
|
||||
return ""
|
||||
}
|
||||
if total > len(masked) {
|
||||
masked = append(masked, fmt.Sprintf("...共%d项", total))
|
||||
}
|
||||
return strings.Join(masked, "; ")
|
||||
}
|
||||
|
||||
func splitCookie(cookie string) []string {
|
||||
var result []string
|
||||
for _, part := range strings.Split(cookie, ";") {
|
||||
trimmed := strings.TrimSpace(part)
|
||||
if trimmed != "" {
|
||||
result = append(result, trimmed)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func splitCookiePair(pair string) (string, string) {
|
||||
idx := strings.Index(pair, "=")
|
||||
if idx < 0 {
|
||||
return strings.TrimSpace(pair), ""
|
||||
}
|
||||
return strings.TrimSpace(pair[:idx]), pair[idx+1:]
|
||||
}
|
||||
|
||||
func maskValue(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return "****"
|
||||
}
|
||||
runes := []rune(value)
|
||||
if len(runes) <= 8 {
|
||||
return "****"
|
||||
}
|
||||
return string(runes[:4]) + "****" + string(runes[len(runes)-4:])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user