Files
dygou_go/internal/proxy/whitelist_lock.go
T
yml 9c83be798d feat: 优化代理准备并完善远端部署
- 增加严格代理、两分钟预取、白名单去重与分组状态展示\n- 增加远端注册令牌和安全地址校验\n- 增加 Docker Compose、Caddy 示例与控制中心部署文档
2026-11-21 20:59:35 +08:00

82 lines
1.8 KiB
Go

package proxy
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"time"
)
const whitelistLockStaleAfter = 2 * time.Minute
const whitelistMarkerTTL = 10 * time.Minute
type whitelistGuard struct {
path string
markerPath string
}
func acquireWhitelistLock(ctx context.Context, baseURL, no, ip string) (*whitelistGuard, error) {
sum := sha256.Sum256([]byte(baseURL + "\x00" + no + "\x00" + ip))
dir := filepath.Join(os.TempDir(), "douyu-go-whitelist")
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
key := hex.EncodeToString(sum[:16])
path := filepath.Join(dir, key+".lock")
guard := &whitelistGuard{
path: path,
markerPath: filepath.Join(dir, key+".ok"),
}
for {
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err == nil {
_, _ = fmt.Fprintf(file, "%d\n%s\n", os.Getpid(), time.Now().Format(time.RFC3339Nano))
_ = file.Close()
return guard, nil
}
if !errors.Is(err, os.ErrExist) {
return nil, err
}
if info, statErr := os.Stat(path); statErr == nil && time.Since(info.ModTime()) > whitelistLockStaleAfter {
_ = os.Remove(path)
continue
}
timer := time.NewTimer(200 * time.Millisecond)
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
case <-timer.C:
}
}
}
func (g *whitelistGuard) recentlyAdded() bool {
if g == nil {
return false
}
info, err := os.Stat(g.markerPath)
if err != nil {
return false
}
age := time.Since(info.ModTime())
return age >= 0 && age < whitelistMarkerTTL
}
func (g *whitelistGuard) markAdded() {
if g == nil {
return
}
_ = os.WriteFile(g.markerPath, []byte(time.Now().Format(time.RFC3339Nano)), 0o600)
}
func (g *whitelistGuard) release() {
if g != nil {
_ = os.Remove(g.path)
}
}