feat: 优化代理准备并完善远端部署

- 增加严格代理、两分钟预取、白名单去重与分组状态展示\n- 增加远端注册令牌和安全地址校验\n- 增加 Docker Compose、Caddy 示例与控制中心部署文档
This commit is contained in:
yml
2026-11-21 20:59:35 +08:00
parent d176c421a8
commit 9c83be798d
43 changed files with 2755 additions and 119 deletions
+314 -18
View File
@@ -21,7 +21,7 @@ import (
const (
proxyFetchRounds = 3
proxyFetchMaxRounds = 20
proxyFetchRetryWait = 300 * time.Millisecond
proxyFetchRetryWait = 1200 * time.Millisecond
proxyRequestTimeout = 15 * time.Second
proxyValidationTimeout = 3 * time.Second
proxyValidationWorkers = 3
@@ -38,6 +38,10 @@ type proxySettingsSnapshot struct {
autoFetchOnTimer bool
accountsPerProxy int
sparePercent int
required bool
ready bool
state string
blockedReason string
autoWhitelist bool
whitelistReplace bool
whitelistPassword string
@@ -55,8 +59,14 @@ type validatedProxy struct {
}
type proxyRuntimeGroup struct {
groupIndex int
accountNames []string
activeURL string
activeIP string
activeRegion string
activeRTT time.Duration
switchCount int
lastError string
consecutiveFailures int
failed bool
}
@@ -90,13 +100,14 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
autoFetch := cfg.AutoFetchProxyOnSchedule
accountsPerProxy := cfg.AccountsPerProxy
sparePercent := cfg.ProxySparePercent
required := cfg.ProxyRequired
if accountsPerProxy <= 0 {
accountsPerProxy = constants.DefaultAccountsPerProxy
}
if accountsPerProxy > constants.MaxAccountsPerProxy {
accountsPerProxy = constants.MaxAccountsPerProxy
}
if sparePercent <= 0 {
if sparePercent < constants.MinProxySparePercent {
sparePercent = constants.DefaultProxySparePercent
}
if sparePercent > constants.MaxProxySparePercent {
@@ -113,6 +124,7 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
s.autoFetchProxyOnSchedule != autoFetch ||
s.accountsPerProxy != accountsPerProxy ||
s.proxySparePercent != sparePercent ||
s.proxyRequired != required ||
s.autoWhitelist != cfg.ProxyAutoWhitelist ||
s.whitelistReplace != cfg.ProxyWhitelistReplace ||
s.whitelistPassword != whitelistPassword ||
@@ -123,6 +135,12 @@ func (s *Scheduler) UpdateProxySettings(cfg types.Config) {
s.autoFetchProxyOnSchedule = autoFetch
s.accountsPerProxy = accountsPerProxy
s.proxySparePercent = sparePercent
s.proxyRequired = required
if changed {
s.proxyReady = false
s.proxyState = "stale"
s.proxyBlockedReason = "代理配置已变更,等待重新准备"
}
s.autoWhitelist = cfg.ProxyAutoWhitelist
s.whitelistReplace = cfg.ProxyWhitelistReplace
s.whitelistPassword = whitelistPassword
@@ -149,7 +167,7 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
size = constants.MaxAccountsPerProxy
}
sparePercent := s.proxySparePercent
if sparePercent <= 0 {
if sparePercent < constants.MinProxySparePercent {
sparePercent = constants.DefaultProxySparePercent
}
if sparePercent > constants.MaxProxySparePercent {
@@ -162,6 +180,10 @@ func (s *Scheduler) proxySettings() proxySettingsSnapshot {
autoFetchOnTimer: s.autoFetchProxyOnSchedule,
accountsPerProxy: size,
sparePercent: sparePercent,
required: s.proxyRequired,
ready: s.proxyReady,
state: s.proxyState,
blockedReason: s.proxyBlockedReason,
autoWhitelist: s.autoWhitelist,
whitelistReplace: s.whitelistReplace,
whitelistPassword: s.whitelistPassword,
@@ -180,6 +202,8 @@ func (s *Scheduler) closeAccountClients() {
s.accountClientsDirty = true
s.accountClientsExpireAt = time.Time{}
s.proxyGroups = make(map[*client.DouyuClient]*proxyRuntimeGroup)
s.proxyGroupHistory = nil
s.accountProxyGroup = make(map[string]int)
s.proxyStandbys = nil
s.proxyClientPool = nil
s.proxyExcludedURLs = make(map[string]struct{})
@@ -211,6 +235,15 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
s.accountClientsDirty = false
s.accountClientsExpireAt = pool.expiresAt
s.proxyGroups = pool.groups
s.accountProxyGroup = make(map[string]int)
for _, group := range pool.groups {
if group == nil {
continue
}
for _, name := range group.accountNames {
s.accountProxyGroup[name] = group.groupIndex
}
}
s.proxyStandbys = pool.standbys
s.proxyClientPool = pool.allClients
s.proxyExcludedURLs = pool.excludedURLs
@@ -222,6 +255,146 @@ func (s *Scheduler) replaceAccountClients(pool preparedProxyPool) {
closeDouyuClientList(oldClients)
}
func (s *Scheduler) replaceProxyGroupHistory(groups [][]string, activeCount int, proxies []validatedProxy) {
history := make([]types.ProxyGroupStatus, 0, activeCount)
for index, accounts := range groups {
if index >= len(proxies) {
break
}
proxy := proxies[index]
history = append(history, types.ProxyGroupStatus{
GroupIndex: index + 1,
Role: "active",
State: "active",
AccountCount: len(accounts),
Accounts: append([]string(nil), accounts...),
Proxy: client.MaskProxyURL(proxy.url),
Region: proxy.region,
RTTMs: proxy.rtt.Milliseconds(),
})
}
s.clientMu.Lock()
s.proxyGroupHistory = history
s.clientMu.Unlock()
}
// ProxyStatus returns a structured status snapshot. It never includes proxy
// credentials and is safe to expose to the desktop and remote dashboards.
func (s *Scheduler) ProxyStatus() types.ProxyStatusView {
cfg := s.proxySettings()
s.clientMu.RLock()
history := make([]types.ProxyGroupStatus, len(s.proxyGroupHistory))
copy(history, s.proxyGroupHistory)
for i := range history {
history[i].Accounts = append([]string(nil), history[i].Accounts...)
}
accountGroups := make(map[string]int, len(s.accountProxyGroup))
for name, index := range s.accountProxyGroup {
accountGroups[name] = index
}
names := make([]string, 0, len(s.accountClients))
for name := range s.accountClients {
names = append(names, name)
}
sort.Strings(names)
groupsByIndex := make(map[int]types.ProxyGroupStatus, len(history))
for _, group := range history {
groupsByIndex[group.GroupIndex] = group
}
accounts := make([]types.AccountProxyView, 0, len(names))
directCount := 0
for _, name := range names {
groupIndex := accountGroups[name]
view := types.AccountProxyView{
AccountName: name,
GroupIndex: groupIndex,
GroupLabel: "未分配",
Transport: "unassigned",
}
if cli := s.accountClients[name]; cli == s.directClient {
view.GroupLabel = "直连"
view.Transport = "direct"
directCount++
} else if groupIndex > 0 {
view.GroupLabel = fmt.Sprintf("G%d", groupIndex)
view.Transport = "proxy"
if group, ok := groupsByIndex[groupIndex]; ok {
view.Proxy = group.Proxy
}
}
accounts = append(accounts, view)
}
standbyCount := len(s.proxyStandbys)
s.clientMu.RUnlock()
activeCount := 0
for _, group := range history {
if group.Role == "active" {
activeCount++
}
}
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
state := cfg.state
if state == "" {
state = "empty"
}
lastError := cfg.blockedReason
switch {
case !cfg.enabled:
state = "disabled"
lastError = ""
case directCount > 0:
state = "direct_fallback"
if lastError == "" {
lastError = "账号已回退直连"
}
case cfg.ready:
state = "ready"
lastError = ""
if reason := proxyDegradedReason(history, standbyCount, standbyTarget); reason != "" {
state = "degraded"
lastError = reason
}
case state == "preparing":
// Keep the explicit preparing state visible while the pool is refreshed.
case lastError != "":
state = "failed"
case len(history) == 0:
state = "empty"
default:
state = "preparing"
}
return types.ProxyStatusView{
Enabled: cfg.enabled,
Required: cfg.required,
State: state,
ActiveCount: activeCount,
StandbyCount: standbyCount,
StandbyTarget: standbyTarget,
DirectCount: directCount,
LastError: lastError,
UpdatedAt: time.Now().In(constants.CST).Format("2006-01-02 15:04:05.000"),
Groups: history,
Accounts: accounts,
}
}
func proxyDegradedReason(groups []types.ProxyGroupStatus, standbyCount, standbyTarget int) string {
failed := 0
for _, group := range groups {
if group.State == "failed" {
failed++
}
}
if failed > 0 {
return fmt.Sprintf("%d 个代理组失败,等待备用代理", failed)
}
if standbyCount < standbyTarget {
return fmt.Sprintf("备用代理不足: %d/%d", standbyCount, standbyTarget)
}
return ""
}
func closeDouyuClients(clients map[string]*client.DouyuClient) {
items := make([]*client.DouyuClient, 0, len(clients))
for _, cli := range clients {
@@ -318,6 +491,14 @@ func (s *Scheduler) allClients() []*client.DouyuClient {
// prepareProxyGroups 将本次参与抢购的账号按固定顺序分组,并为每组准备独立客户端。
// forceRefresh=true 用于定时任务启动前主动刷新短效代理。
func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceRefresh bool) error {
timeout := proxyImmediateTimeout
if forceRefresh {
timeout = proxyScheduledTimeout
}
return s.prepareProxyGroupsUntil(accountProducts, forceRefresh, time.Now().Add(timeout))
}
func (s *Scheduler) prepareProxyGroupsUntil(accountProducts map[string]string, forceRefresh bool, deadline time.Time) error {
s.proxyPrepareMu.Lock()
defer s.proxyPrepareMu.Unlock()
@@ -328,38 +509,38 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
}
if !cfg.enabled {
s.closeAccountClients()
s.setProxyReadiness(false, "代理未启用")
return nil
}
if !forceRefresh && s.proxyFallbackSnapshot() {
if !forceRefresh && !cfg.required && s.proxyFallbackSnapshot() {
logger.LogEvent("代理", "warn", "代理此前准备失败,本次抢购直接使用直连,避免再次等待")
return nil
}
if !forceRefresh && s.accountClientsCover(names) {
s.setProxyReadiness(true, "")
return nil
}
s.setProxyPreparing("代理正在准备")
groups := chunkAccountNames(names, cfg.accountsPerProxy)
activeCount := len(groups)
standbyTarget := proxyStandbyCount(activeCount, cfg.sparePercent)
base := s.clientSnapshot()
if base == nil {
s.activateProxyDirectFallback(errors.New("基础客户端未初始化"))
return nil
return s.handleProxyPrepareFailure(cfg, names, errors.New("基础客户端未初始化"))
}
poolStartedAt := time.Now()
timeout := proxyImmediateTimeout
if forceRefresh {
timeout = proxyScheduledTimeout
timeout := time.Until(deadline)
if timeout <= 0 {
return s.handleProxyPrepareFailure(cfg, names, errors.New("代理准备截止时间已到"))
}
proxies, err := s.buildProxyPool(base, cfg, activeCount, activeCount+standbyTarget, nil, timeout)
if err != nil {
s.activateProxyDirectFallback(err)
return nil
return s.handleProxyPrepareFailure(cfg, names, err)
}
if len(proxies) < activeCount {
s.activateProxyDirectFallback(fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
return nil
closeValidatedProxies(proxies)
return s.handleProxyPrepareFailure(cfg, names, fmt.Errorf("代理数量不足: 需要%d个活动代理,实际%d个", activeCount, len(proxies)))
}
if len(proxies) < activeCount+standbyTarget {
logger.LogEvent("代理", "warn", "备用代理不足: 目标%d个,实际%d个;活动代理不受影响",
@@ -373,8 +554,12 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
proxy := proxies[i]
clientOrder = append(clientOrder, proxy.client)
runtimeGroups[proxy.client] = &proxyRuntimeGroup{
groupIndex: i + 1,
accountNames: append([]string(nil), group...),
activeURL: proxy.url,
activeIP: proxy.ip,
activeRegion: proxy.region,
activeRTT: proxy.rtt,
}
for _, name := range group {
accountClients[name] = proxy.client
@@ -394,6 +579,7 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
s.recordProxyResult(proxyClient, err)
})
}
poolStartedAt := time.Now()
expiresAt := time.Time{}
if cfg.proxyAPI != "" {
expiresAt = proxyPoolExpiresAt(cfg.proxyAPI, poolStartedAt)
@@ -416,11 +602,60 @@ func (s *Scheduler) prepareProxyGroups(accountProducts map[string]string, forceR
standbyTarget: effectiveProxyStandbyTarget(cfg, standbyTarget, len(standbys)),
expiresAt: expiresAt,
})
s.replaceProxyGroupHistory(groups, activeCount, proxies)
logger.LogEvent("代理", "success", "代理池准备完成: 账号=%d,每组=%d,活动代理=%d,备用代理=%d/%d",
len(names), cfg.accountsPerProxy, activeCount, len(standbys), standbyTarget)
s.setProxyReadiness(true, "")
return nil
}
func (s *Scheduler) handleProxyPrepareFailure(cfg proxySettingsSnapshot, names []string, cause error) error {
if cfg.required {
s.closeAccountClients()
s.setProxyReadiness(false, cause.Error())
logger.LogEvent("代理", "error", "严格代理模式准备失败,本次不启动且不回退直连: %v", cause)
return cause
}
s.activateProxyDirectFallback(cause)
s.setDirectFallbackAccounts(names)
return nil
}
func (s *Scheduler) setDirectFallbackAccounts(names []string) {
s.clientMu.Lock()
if s.directClient != nil {
s.accountClients = make(map[string]*client.DouyuClient, len(names))
for _, name := range names {
s.accountClients[name] = s.directClient
}
s.accountClientOrder = []*client.DouyuClient{s.directClient}
s.accountClientsDirty = false
}
s.clientMu.Unlock()
}
func (s *Scheduler) setProxyReadiness(ready bool, reason string) {
s.proxyMu.Lock()
s.proxyReady = ready
if ready {
s.proxyState = "ready"
} else if reason != "" {
s.proxyState = "failed"
} else {
s.proxyState = "empty"
}
s.proxyBlockedReason = reason
s.proxyMu.Unlock()
}
func (s *Scheduler) setProxyPreparing(reason string) {
s.proxyMu.Lock()
s.proxyReady = false
s.proxyState = "preparing"
s.proxyBlockedReason = reason
s.proxyMu.Unlock()
}
func (s *Scheduler) proxyFallbackSnapshot() bool {
s.clientMu.RLock()
defer s.clientMu.RUnlock()
@@ -434,9 +669,11 @@ func (s *Scheduler) activateProxyDirectFallback(cause error) {
s.proxyFallbackActive = active
s.clientMu.Unlock()
if active {
s.setProxyReadiness(false, cause.Error())
logger.LogEvent("代理", "warn", "代理准备失败,已回退直连以保证抢购继续: %v", cause)
return
}
s.setProxyReadiness(false, cause.Error())
logger.LogEvent("代理", "error", "代理准备失败且直连客户端不可用: %v", cause)
}
@@ -452,6 +689,10 @@ func (s *Scheduler) PrepareProxyGroups(accountProducts map[string]string) error
return s.prepareProxyGroups(accountProducts, false)
}
func (s *Scheduler) PrepareProxyGroupsUntil(accountProducts map[string]string, deadline time.Time) error {
return s.prepareProxyGroupsUntil(accountProducts, true, deadline)
}
func selectedAccountNames(accountProducts map[string]string) []string {
names := make([]string, 0, len(accountProducts))
for name, productID := range accountProducts {
@@ -487,7 +728,7 @@ func proxyStandbyCount(activeCount, sparePercent int) int {
if activeCount <= 0 {
return 0
}
if sparePercent <= 0 {
if sparePercent < constants.MinProxySparePercent {
sparePercent = constants.DefaultProxySparePercent
}
if sparePercent > constants.MaxProxySparePercent {
@@ -726,6 +967,7 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
if proxyClient == nil {
return
}
cfg := s.proxySettings()
s.clientMu.Lock()
group := s.proxyGroups[proxyClient]
@@ -735,6 +977,8 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
}
if err == nil {
group.consecutiveFailures = 0
group.lastError = ""
s.updateProxyGroupHistoryLocked(group)
s.clientMu.Unlock()
return
}
@@ -744,6 +988,8 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
}
group.consecutiveFailures++
group.lastError = err.Error()
s.updateProxyGroupHistoryLocked(group)
if group.consecutiveFailures < 2 {
failures := group.consecutiveFailures
activeURL := group.activeURL
@@ -753,7 +999,9 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
}
event, expiredClients, switched := s.switchGroupToStandbyLocked(proxyClient, group)
if !switched && s.directClient != nil {
if !switched && cfg.required {
group.failed = true
} else if !switched && s.directClient != nil {
event = s.switchGroupToDirectLocked(proxyClient, group)
switched = true
}
@@ -767,6 +1015,7 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
failedAccounts = len(group.accountNames)
failedURL = group.activeURL
needRefill = !s.proxyRefillInFlight
s.updateProxyGroupHistoryLocked(group)
}
s.clientMu.Unlock()
@@ -774,8 +1023,13 @@ func (s *Scheduler) recordProxyResult(proxyClient *client.DouyuClient, err error
if switched {
logProxySwitch("代理故障切换", event)
} else {
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
failedAccounts, client.MaskProxyURL(failedURL))
if cfg.required {
logger.LogEvent("代理", "warn", "严格代理模式下代理组连续失败且暂无备用,暂不直连并等待补提取: 账号=%d 出口=%s",
failedAccounts, client.MaskProxyURL(failedURL))
} else {
logger.LogEvent("代理", "warn", "代理组连续失败且暂无备用: 账号=%d 出口=%s,正在尝试补提取",
failedAccounts, client.MaskProxyURL(failedURL))
}
}
if needRefill {
s.startProxyRefill()
@@ -802,7 +1056,12 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
toSource: standby.source,
}
group.activeURL = standby.url
group.activeIP = standby.ip
group.activeRegion = standby.region
group.activeRTT = standby.rtt
group.switchCount++
group.consecutiveFailures = 0
group.lastError = ""
group.failed = false
for _, accountName := range group.accountNames {
s.accountClients[accountName] = standby.client
@@ -810,6 +1069,7 @@ func (s *Scheduler) switchGroupToStandbyLocked(oldClient *client.DouyuClient, gr
delete(s.proxyGroups, oldClient)
s.proxyGroups[standby.client] = group
replaceClientInOrder(s.accountClientOrder, oldClient, standby.client)
s.updateProxyGroupHistoryLocked(group)
return event, expiredClients, true
}
return proxySwitchEvent{}, expiredClients, false
@@ -821,16 +1081,52 @@ func (s *Scheduler) switchGroupToDirectLocked(oldClient *client.DouyuClient, gro
fromURL: group.activeURL,
}
group.activeURL = ""
group.activeIP = ""
group.activeRegion = ""
group.activeRTT = 0
group.switchCount++
group.consecutiveFailures = 0
group.lastError = ""
group.failed = false
for _, accountName := range group.accountNames {
s.accountClients[accountName] = s.directClient
}
delete(s.proxyGroups, oldClient)
replaceClientInOrder(s.accountClientOrder, oldClient, s.directClient)
s.updateProxyGroupHistoryLocked(group)
return event
}
func (s *Scheduler) updateProxyGroupHistoryLocked(group *proxyRuntimeGroup) {
if group == nil || group.groupIndex <= 0 {
return
}
for i := range s.proxyGroupHistory {
item := &s.proxyGroupHistory[i]
if item.GroupIndex != group.groupIndex {
continue
}
item.AccountCount = len(group.accountNames)
item.Accounts = append([]string(nil), group.accountNames...)
item.SwitchCount = group.switchCount
item.LastError = group.lastError
switch {
case group.activeURL == "":
item.State = "direct"
item.Proxy = ""
item.Region = ""
case group.failed:
item.State = "failed"
default:
item.State = "active"
item.Proxy = client.MaskProxyURL(group.activeURL)
item.Region = group.activeRegion
item.RTTMs = group.activeRTT.Milliseconds()
}
return
}
}
func replaceClientInOrder(order []*client.DouyuClient, oldClient, newClient *client.DouyuClient) {
for i, cli := range order {
if cli == oldClient {